I have a question about how to use QAudioOutput to directly record a sample with a specific sampling rate to a sound output device. I write an emulator that emulates sound chips based on a frame, and then receives a buffer containing a frame, which stands for sound samples that I would like to record on the audio output. Currently, to test my sound output routine, I allocate a huge (5-minute) buffer for entering random numbers, for example:
Title:
uint16_t *audio_outputBuffer;
uint32_t audio_bytesRemainingToRead;
QAudioOutput *audio_outputStream;
QIODevice *audio_outputDevice;
Implementation:
audio_outputBuffer = (uint16_t *) malloc((96000 * 4) * 300);
int i = 0;
uint16_t *tempAudioBuffer = audio_outputBuffer;
for(i = 0; i < ((96000 * 4) * 150); i++) {
*tempAudioBuffer = (uint16_t) rand() & 0xFFFF;
tempAudioBuffer++;
}
audio_bytesRemainingToRead = (96000 * 4) * 300;
Then I set up my audio device with some basic parameters:
QAudioFormat format;
format.setFrequency(96000);
format.setChannels(2);
format.setSampleSize(16);
format.setCodec("audio/pcm");
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::UnSignedInt);
audio_outputStream = new QAudioOutput(format, this);
connect(audio_outputStream, SIGNAL(stateChanged(QAudio::State)), this, SLOT(audio_stateChanged(QAudio::State)));
audio_outputDevice = audio_outputStream->start();
Then, in my timer procedure, which QTimer calls at 60 FPS, I do the following code to write a โchunkโ of audio data to the QAudioOutput buffer:
if(audio_outputDevice->isOpen() && audio_outputStream->state() != QAudio::StoppedState) {
qint64 bytesOfAudioWrittenToDevice = audio_outputDevice->write((char *) audio_outputBuffer, audio_outputStream->periodSize());
audio_bytesRemainingToRead -= bytesOfAudioWrittenToDevice;
qDebug() << "Wrote" << bytesOfAudioWrittenToDevice << "bytes of audio to output device. Remaining bytes to read:" << audio_bytesRemainingToRead;
qDebug() << "Free bytes in audio output:" << audio_outputStream->bytesFree();
}
As soon as I started the audio output process, I get the following output on the console:
Current audio state: 3 Error: 0
Wrote 2048 bytes of audio to output device. Remaining bytes to read: 115197952
Free bytes in audio output: 6144
Current audio state: 0 Error: 0
Wrote 2048 bytes of audio to output device. Remaining bytes to read: 115195904
Free bytes in audio output: 4096
Wrote 2048 bytes of audio to output device. Remaining bytes to read: 115193856
Free bytes in audio output: 2048
Wrote 2048 bytes of audio to output device. Remaining bytes to read: 115191808
Free bytes in audio output: 0 (This and the above line is repeated forever)
, QAudioOutput , " , ".
?
(, Qt 4.8.1, Mac OS X 10.7.4.)
.