Question

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.

Was it helpful?

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"));

OTHER TIPS

You should at least connect the signal stateChanged(Phonon::State, Phonon::State) from your MediaObject object to a custom slot to detect errors: if the state changes to Phonon::ErrorState the reason of the error might be accessible through QMediaObject::errorString().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top