Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Program crashes trying to play audio using QAudioOutput



  • I am trying to use QAudioOutput to play an endless sine wave from a byte array. When I run it, the program crashes just after the audio device's state changes to ActiveState. When I use debugging mode, it says the crash occurs in QBuffer::readData(). Here is the creation of the buffer I am trying to use:

    QByteArray buffer;
    
    for (int i = 0; i < SAMPLE_RATE; i++)
    {
        buffer.append(QString("%1").arg(sin(2 * M_PI * (double)i / SAMPLE_RATE)));
    }
    
    audioPlayer->play(&buffer);
    

    Here is the play function in AudioPlayer:

    void AudioPlayer::play(QByteArray *data)
    {
        QMetaObject::invokeMethod(&audioThread, "play", Qt::QueuedConnection, Q_ARG(QByteArray, *data));
    }
    

    Here is the play function in AudioThread (buffer is a QBuffer member variable):

    void AudioThread::play(QByteArray data)
    {
        buffer.setBuffer(&data);
        buffer.open(QIODevice::ReadOnly);
    
        audioOutput->setBufferSize(buffer.size());
        audioOutput->start(&buffer);
    }
    

    The last line of play in AudioThread is the last line that I can trace in my code before the error occurs, and I'm guessing it is the line with the problem, because I never hear any audio. Thanks in advance for your help, and let me know if I should include any other sections of my code.



  • @ERSUCC said in Program crashes trying to play audio using QAudioOutput:

    buffer.setBuffer(&data);

    I think this line is the cause of the crash.
    data here is a local variable, it will be destroyed at the end of this function.
    You set buffer to use it as internal buffer, but it is not accessible after that.

    void QBuffer::setBuffer(QByteArray *byteArray)
    ...
    The caller is responsible for ensuring that byteArray remains valid until the QBuffer is destroyed, or until setBuffer() is called to change the buffer.

    Try use buffer.setData(data) instead.



  • That worked! Thank you so much!


Log in to reply