Search code examples
c++qtaudioqt6

Qt AudioSource not recording


What I want to do is to record some audio in a console application.

QBuffer buffer;
buffer.open(QBuffer::ReadWrite);

QAudioFormat format;
format.setSampleRate(8000);
format.setChannelCount(1);
format.setSampleFormat(QAudioFormat::UInt8);

QAudioDevice info = QMediaDevices::defaultAudioInput();
if(!info.isFormatSupported(format))
{
    std::cout << "Default format not supported";
}

QAudioSource source(format);
assert(source.state() == QAudio::StoppedState);

source.setVolume(1);
source.start(&buffer);

if(source.error() or source.state() != QAudio::ActiveState)
{
    std::cout << "An error has occured while recording audio" << std::endl;
    return;
}

hasInitialisedAudio = true;

do
{
    sleep(10)

    source.stop();
    buffer.seek(0);
    std::cout << "Recorded a buffer of size " << buffer.size() << " during " << source.processedUSecs() << " second." << std::endl;
    double RMS = calculateRMS(buffer.data().constData(), buffer.size());
}
while(true);

However, this gives me a buffer.size() of 0 and a source.processedUSecs() of 0.

How do I fix this?


Solution

  • You need to pump the message loop. You would need to create a QApplication and call exec on it. This would block your thread endlessly (your while loop). From there on, you would rather program with signal slots (events).

    For a console application, it should rather be QCoreApplication.