当前位置:网站首页>Player actual combat 12 QT playing audio

Player actual combat 12 QT playing audio

2022-06-12 14:08:00 Sister Suo

We mainly use the following three classes :
QAudioDeviceInfo Class provides an audio output device
QAudioFormat Class provides audio parameter settings
QAudioOutput Class provides the PCM The interface that sends raw audio data to the audio output device .

1. Import the header file and open PCM file

#include <QtCore/QCoreApplication>
#include<qaudioformat.h>
#include<qaudiooutput.h>
#include<qthread.h>
#include<iostream>
using namespace std;
int main(int argc, char *argv[])
{
    
    QCoreApplication a(argc, argv);
    FILE* fp = fopen("test.pcm","rb");
    if (fp)
        cout << " Open the success " << endl;
    else
        cout << " Open the failure " << endl;

2. Instantiation QAudioFormat And set the parameters

 QAudioFormat fmt;
    fmt.setSampleRate(44100);
    fmt.setSampleSize(16);// Number of sampling bits 
    fmt.setChannelCount(2);
    fmt.setCodec("audio/pcm");
    fmt.setByteOrder(QAudioFormat::LittleEndian);// Byte order , Not bitwise , such as 16, The small end 16 Big end 61
    fmt.setSampleType(QAudioFormat::UnSignedInt);
    

3. Open up a QAudioOutput Space , Use the object instantiated above fmt As its new Make the constructor arguments
And call QAudioOutput Of start Method to start playing ( Just turned on the switch , The data has not yet started to flow , To hear the playing sound, you need to use io->wirte() take PCM Data to play )

QAudioOutput* out = new QAudioOutput(fmt);
QIODevice* io = out->start();

4. Put the audio data to be played into the buffer queue in batches and play

   int size = out->periodSize();
    char* buf = new char[size];
    
    while (!feof(fp))
    {
    
        if (out->bytesFree() < size)
        {
    
            QThread::msleep(1);
            continue;
        }
        int len=fread(buf, 1, size, fp);
        if (len <= 0)
            break;
        io->write(buf, len);
    }
    fclose(fp);
    delete buf;
    buf = 0;
    return a.exec();
}

out->periodSize() Is the size of the incoming data

When the free size of the buffer is smaller than the size of the data put in at one time , Has reached the awaited , Wait until the extra data in the buffer is played and enough space is left before putting data into the buffer , Judge with the following statement if (out->bytesFree() < size)

int len=fread(buf, 1, size, fp); take fp Point to the PCM The data reads buf in

use buf As a media connection QT Original documents

io->write(buf, len);// Resampled PCM Pass to QT, Just started playing

原网站

版权声明
本文为[Sister Suo]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010513447095.html