Important: Please read the Qt Code of Conduct -

How to generate audio stream in realtime?

  • Hi,
    I'm working on an embedded device which is measureing a gas concentration. The value should be displayed as number and also the level should be audible. The higher the level the more klicks per second should be played (e.g. 10% -> 10 Klicks per second / 100% -> 100 Klicks per second). Similar to a Geiger counter.
    Currently I measure the level and generate a buffer with the audio data (wav-format).

    The following code shows only the significant parts of the code. It works, but with problems.

    QMediaPlayer *m_player;
    QBuffer *m_stream;
    QByteArray m_audioHeader;
    QByteArray m_audioData;
    void GasSensor::myFunction() {
    m_player->setMedia(QMediaContent(), m_stream);
    connect(m_timerRefresh, &QTimer::timeout, this, &GasSensor::refresh, Qt::UniqueConnection);
    void GasSensor::refresh() {
    	//... get current gas concentration level
    	//... generate newAudioData with Klick-Sound
    	// Samplerate = 8kHz / Samplesize = 16 bit
    	//Copy audiodata to stream buffer (double buffer principle)
    	if( m_currentBufferNum == 1 ) {
    		m_currentBufferNum = 0;
    		m_player->setPosition(0);	//--> this leads to additional unwanted pause and klicks
    	} else {
    		m_currentBufferNum = 1;
    		m_player->setPosition(1000);   //--> this leads to additional unwanted pause and klicks

    The audio data is played continously but every time I set a new play position (m_player->setPosition()) I get two problems. First: The play position is not updated fast enough and a small pause (some milliseconds) is audible. Second: The pulse-pause-ratio is changed because the refresh-function is not called exacly every 1000 ms. I understand that this is a normal behaviour and I'm searching for a workaround.
    I have the following idea but I couldn't find a solution to solve it:
    A stream should be generated and played continiously. The part with the new audio data (klick-sounds) should be added to the stream some milliseconds (e.g. 100-200 ms) before the play position. The buffer of the audioplayer should not be increased because of limited memory available. Similar to a webradio stream. But I don't need to store or buffer old data.

    Has anyone an idea how to generate and play audio data in realtime?
    Thanks in advance for your comments.

  • Hi @_M_H_
    Just an idea, but would changing the playbackRate work for you?
    Have one sound that you loop and change the playback rate of that.

    P.S. I haven't done anything with multimedia in a couple of years, so it's just an idea.

  • Thanks for your idea. But this is no solution for me, because the pulse width should be alwas the same. Only the pause time shoud vary. If I increase the playback rate, both will be changed.

Log in to reply