Nyaruko
Nyaruko

Reputation: 4479

Continuous warning sound in Qt?

What is the easiest way to play a continuous warning sound that lasts several minutes without affecting the main thread's performance? I know that QSound can work in asynchronous mode, however, according to here: Qt: How to play sound witout blocking main thread? QSound would still bring noticeable affect on the main thread.

Is there any simple solution to this?

Upvotes: 1

Views: 545

Answers (1)

Jablonski
Jablonski

Reputation: 18504

As suggested earlier, try to play sound in another thread. But QSound has not enough signals to control it. If you want get deeper control you can use QSoundEffect Try this:

header:

#ifndef WORKER_H
#define WORKER_H

#include <QObject>

class Worker : public QObject
{
    Q_OBJECT
public:
    explicit Worker(QObject *parent = 0);


signals:

public slots:
    void process();

};

#endif // WORKER_H

Cpp

#include "worker.h"
#include <QSound>

Worker::Worker(QObject *parent) :
    QObject(parent)
{
}

void Worker::process()
{
    QSound *sound = new QSound("path");
    sound->setLoops(100);
    sound->play();
}

Usage:

QThread *thr = new QThread;
Worker * work = new Worker;
connect(thr, SIGNAL(started()), work, SLOT(process()));
work->moveToThread(thr);
thr->start();

To play it several minutes you can set infinite number of loops and use QTimer (maybe singleShot) to end thread and delete object(music will be stopped too).

Upvotes: 1

Related Questions