Search code examples
qtqt-creatorphonon

Phonon Qt - play sound on button click


I need to play a sound when a button is clicked, I have this:

Phonon::MediaObject *clickObject = new Phonon::MediaObject(this);
clickObject->setCurrentSource(Phonon::MediaSource("Click/sound.wav");
Phonon::AudioOutput *clickOutput = new Phonon::AudioOutput(Phonon::MusicCategory, this);
Phonon::createPath(clickObject, clickOutput);

and

void MainWindow::on_pushButton_clicked()
{
   clickObject->play();
}

but no sound is played? Where am I wrong? Thanks. EDIT: It works now, it was the wrong path.


Solution

  • Probably the file path "Click/sound.wav" doesn't point where you think it points.

    Try this before calling the setCurrentSource()-function:

    bool exists = QFile::exists("Click/sound.wav");
    

    If the Click directory is supposed to be in the same directory as your exe, create the path like this:

    QString filePath = QCoreApplication::applicationDirPath() + "/Click/sound.wav";
    clickObject->setCurrentSource(Phonon::MediaSource(filePath));
    

    And I would suggest using Qt resource system. Then you would point to the sound file like this:

    clickObject->setCurrentSource(Phonon::MediaSource(":/Click/sound.wav"));