Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Update: Forum Guidelines & Code of Conduct

    Solved Program crashes trying to play audio using QAudioOutput

    General and Desktop
    2
    3
    212
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • E
      ERSUCC last edited by

      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.

      1 Reply Last reply Reply Quote 0
      • B
        Bonnie last edited by Bonnie

        @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.

        1 Reply Last reply Reply Quote 6
        • E
          ERSUCC last edited by

          That worked! Thank you so much!

          1 Reply Last reply Reply Quote 0
          • First post
            Last post