JohnJohnsonJoe
JohnJohnsonJoe

Reputation: 215

Qt 5 Play wav sound while input from user

My program alerts the user when something has happened. To get his attention, a alert sound plays. It stops when the user enter something to confirm receipt.

But the QTextStream input blocks the sound ! When I remove it, the sound plays perfectly.

Besides, the "alert" QSound object doesn't work. The only way to play is to use the static function QSound::play("file.wav"). But it can't be stopped.

Here is my code :

#include <QCoreApplication>
#include <QSound>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    /*
    QSound alert("../SoundAlerte/alert.wav");
    alert.setLoops(QSound::Infinite);
    alert.play();
    */

    QSound::play("../SoundAlerte/alert.wav");

    qDebug() << "ALERT";
    qDebug() << "Enter Something to confirm receipt" ;

    QTextStream s(stdin);
    QString value = s.readLine();

    qDebug() << "Received !";

    //alert.stop();

    qDebug() << "Sound stopped";

    return a.exec();
}

It seems like it can't play a sound and wait for input at the same time !

Do you have have an idea on how to proceed ?

Thanks

Upvotes: 0

Views: 1214

Answers (1)

Michael Schm.
Michael Schm.

Reputation: 2534

QSound::play is asynchron, but

QString value = s.readLine();

contains a do-while and will block the audio file. See scan function called by readLine()

A working example would be QtConcurrent, but you can't stop the audio file, so you might want to switch to a real QThread approach.

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QFuture<void> future = QtConcurrent::run([]() {
        QSoundEffect effect;
        QEventLoop loop;
        effect.setSource(QUrl::fromLocalFile("C:\\piano2.wav"));
        effect.setVolume(0.25f);
        effect.play();
        QObject::connect(&effect, &QSoundEffect::playingChanged, [&loop]() { qDebug() << "finished"; loop.exit(); });
        loop.exec();
    });

    QTextStream s(stdin);
    QString value = s.readLine();

    return a.exec();
}

Upvotes: 1

Related Questions