2

I am using QAudioInput to record audio from the system default input device. I get a callback from QIODevice::readyRead that bytes are ready for read, but reading the bytes return an array of \0 's, equal to the size of the audioInput->bytesReady().

What am I doing wrong here and I cannot get the actual bytes recorded from the device?

This is the complete code:

file main.cpp

 #include "mainwindow.h"
    #include "audiorecorder.h"
    #include <QApplication>

    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        MainWindow w;
        w.show();

        AudioRecorder recorder;
        recorder.startRecording();

        return a.exec();
    }

file audiorecorder.h

#ifndef AUDIORECORDER_H
#define AUDIORECORDER_H

#include <QObject>
#include <QAudioInput>

class AudioRecorder : public QObject
{
    Q_OBJECT
public:
    explicit AudioRecorder(QObject *parent = nullptr);

    void startRecording();
private:
    QAudioInput *audioInput;
    QAudioDeviceInfo deviceInfo;
    QAudioFormat format;
    QIODevice *iodevice;
    QAudioDeviceInfo devInfo;

    void onReadyRead();

signals:

};

#endif // AUDIORECORDER_H

file audiorecorder.cpp

#include "audiorecorder.h"
#include <iostream>

AudioRecorder::AudioRecorder(QObject *parent) : QObject(parent)
{

}

void AudioRecorder::startRecording()
{
    deviceInfo = deviceInfo.defaultInputDevice();
    std::cout << deviceInfo.deviceName().toStdString() << std::endl;

    format = deviceInfo.preferredFormat();

    format.setSampleRate(44100);
    format.setChannelCount(1);
    format.setSampleSize(16);
    format.setCodec("audio/pcm");
    format.setByteOrder(QAudioFormat::LittleEndian);
    format.setSampleType(QAudioFormat::SignedInt);

    if (!deviceInfo.isFormatSupported(format)) {
        std::cout << "raw audio format not supported by backend, finding closest alternative." << std::endl;
        format = deviceInfo.nearestFormat(format);
    }

    audioInput = new QAudioInput(deviceInfo, format, this);

    iodevice = audioInput->start();
    QObject::connect(AudioRecorder::iodevice, &QIODevice::readyRead, this, &AudioRecorder::onReadyRead);
}

void AudioRecorder::onReadyRead()
{
    QByteArray buffer;
    auto bytesReady = audioInput->bytesReady();
    std::cout << "bytesReady: " << bytesReady << std::endl;
    buffer.resize(bytesReady);
    //buffer.fill(0);
    auto ret = iodevice->read(buffer.data(), bytesReady);
    std::cout << "bytes read: " << ret << std::endl;
}

I uploaded the complete project code here: https://www.sendspace.com/file/99dlei

Yiannis Mpourkelis
  • 1,366
  • 1
  • 15
  • 34

0 Answers0