How can I play sound with 开发者_开发百科Qt? I tried this:
QSound::play("sounds/croack.wav");
QSound doesn't work on my ubuntu (seems that it requires NAS, although after I installed it it still doesn't work). Is there a simple one line Qt-only solution or do I need to throw in SDL or something else?
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();
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 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.
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.
Ok I have some progress, I can play ogg files but not wav (dunno why).
#include <QtGui>
#include <phonon/phonon>
int main(int argc, char* argv[]) {
QApplication app( argc, argv );
app.setApplicationName("bla");
Phonon::MediaObject *mediaObject = Phonon::createPlayer(Phonon::NoCategory, Phonon::MediaSource("sounds/4.wav"));
mediaObject->play();
return app.exec();
}
Compiled with g++ ``pkg-config QtGui phonon --cflags --libs``
.
I got that trouble too, i've solved it installing this package
qtmultimedia5-dev
and including in the ".pro" file
QT += multimedia
精彩评论