我有一个关于使用 QAudioOutput 以特定采样率将样本直接写入声音输出设备的问题。我正在编写一个模拟器,它在每帧的基础上模拟声音芯片,然后获取一个包含一帧音频样本的缓冲区,我想将其写入音频输出。目前,为了测试我的音频输出例程,我分配了一个巨大的(5 分钟)缓冲区来放入随机数,如下所示:
标题:
uint16_t *audio_outputBuffer;
uint32_t audio_bytesRemainingToRead;
QAudioOutput *audio_outputStream;
QIODevice *audio_outputDevice;
执行:
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;
接下来,我使用一些基本参数设置我的音频设备:
// Set up the format
QAudioFormat format;
format.setFrequency(96000); // Usually this is specified through an UI option
format.setChannels(2);
format.setSampleSize(16);
format.setCodec("audio/pcm");
format.setByteOrder(QAudioFormat::LittleEndian);
format.setSampleType(QAudioFormat::UnSignedInt);
// There's code here to notify the user of inability to match the format and choose an action, which is omitted for clarity
// Create audio output stream, set up signals
audio_outputStream = new QAudioOutput(format, this);
connect(audio_outputStream, SIGNAL(stateChanged(QAudio::State)), this, SLOT(audio_stateChanged(QAudio::State)));
audio_outputDevice = audio_outputStream->start();
然后,在由 QTimer 以 60 FPS 调用的计时器滴答例程中,我执行以下代码将音频数据“块”写入 QAudioOutput 的缓冲区:
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();
}
一旦我开始音频输出过程,我会在控制台上得到以下输出:
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 没有将其内部缓冲区刷新到声卡,这与整个“我的计算机没有声音”的事情有关。
什么会导致这个问题,我该如何解决?
(顺便说一句,我正在 Mac OS X 10.7.4 上针对 Qt 4.8.1 编译我的代码。)
感谢您的任何回答。