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

Can't get QSoundEffect to play



  • Hi,

    I wrote a very simple program to play .wav file which I got from c:/Windows/Media. For some reason when I try to play the wav file nothing happens. I even copied the audio dll's from my Qt 5.12.2 folder into the bin folder where the program exe files live.

    Below is the program.
    #include "mainwindow.h"
    #include "ui_mainwindow.h"

    MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    {
    ui->setupUi(this);

    playSound();
    

    }

    MainWindow::~MainWindow()
    {
    delete ui;
    }

    void MainWindow::playSound()
    {
    QSoundEffect effect;
    QString consoleBinDir(QApplication::applicationDirPath());
    QString waveFile = QDir::cleanPath(consoleBinDir + "/Alarm01.wav");
    effect.setSource(QUrl::fromLocalFile(waveFile));
    qDebug() << QUrl::fromLocalFile(waveFile);
    effect.setLoopCount(1);
    effect.setVolume(1.0);
    effect.play();
    }
    When I print out QUrl::fromLocalFile(waveFile) I get "QUrl("file:///C:/Qt-development/build-sound-Desktop_Qt_5_15_2_MSVC2019_64bit-Debug/debug/Alarm01.wav")" which seems correct. The wave file is certainly located there.

    Can someone please explain to me what I'm doing wrong? It's only a few lines of code!

    Thanks


  • Lifetime Qt Champion

    @leinad said in Can't get QSoundEffect to play:

    QSoundEffect effect;

    Basic C++ - how long does this object live?



  • It exists I guess after the play() is called, how can I make it live until the play is completed? I tried putting a QThread::sleep after the play to hold the tread but still no sound.


  • Lifetime Qt Champion

    @leinad said in Can't get QSoundEffect to play:

    ow can I make it live until the play is completed?

    Again c++ basics - you can e.g. make it a member of your class.


  • Lifetime Qt Champion

    @leinad said in Can't get QSoundEffect to play:

    I tried putting a QThread::sleep after the play to hold the tread but still no sound.

    ?!
    Make effect a class member, or allocate it on the heap...



  • Got it! It works thanks!


Log in to reply