How to play sound with Qt
In QT5, Phonon has been removed from the official build. QSound works for the most part, but note that QSound does not support playing wave files with all sample rates( as I discovered the hard way). QT5 QSound does not play all wave files.
If you use QSound, you can just play a wave like you did; but make sure you are playing a file from a disk; not a QT resource. Since the resources are not supported yet. You can copy a wave file from a resource to a harddrive on the fly and then play it; which is what I am doing in my application.
You have a few options:
- QSound (which is broken beyond repair - don't use it)
- Phonon (will do what you want, but I found it to be "too much", especially when you just want to play a few notification sounds)
- Other libraries like SDL.
Try with phonon. It's far more powerful than QSound. Here's a minimal example to play a video file. If you omit the VideoWidget, it should just play audio.
#include <QApplication>
#include <QUrl>
#include <phonon/audiooutput.h>
#include <phonon/mediaobject.h>
#include <phonon/mediasource.h>
#include <phonon/videowidget.h>
using namespace Phonon;
int main( int argc, char** argv ) {
QApplication app( argc, argv );
app.setApplicationName( QLatin1String("testphonon") );
const QUrl url = QUrl( QLatin1String("file:///somepath/somefile") );
MediaSource src( url );
MediaObject obj;
obj.setCurrentSource( src );
VideoWidget video;
video.show();
AudioOutput audio( VideoCategory );
Phonon::createPath( &obj, &video );
Phonon::createPath( &obj, &audio );
obj.play();
return app.exec();
}
You can use QMediaPlayer for both files format .mp3 and .wav
#include <QtMultimedia/QMediaPlayer>
QMediaPlayer *player = new QMediaPlayer;
player->setMedia(QUrl::fromLocalFile("/path"));
player->setVolume(50);
player->play();