Qt: How to play sound witout blocking main thread?

2019-01-25 23:22发布

I'm wondering is there a simple way in Qt to play sound without blocking the main thread ?

I know that normaly I should start a seperate thread to do this. But maybe there is a shortcut ? :)

Thanks for help.

标签: c++ qt qt4 audio
4条回答
Root(大扎)
2楼-- · 2019-01-25 23:41

The standard QSound and the Phonon library both have significant problems when it comes to playing sound. They both require the main message loop which means either a slight block in the main thread or a delay in playing the sound. Ultimately they both use a background thread, but the lag is easy to notice. Not to mention that Phonon has questionable support on many platforms.

I've worked with both for a while and tried to a build a simple sound system for playing user interface sounds (just to beep and pop occasionally). It just isn't possible using the standard Qt Library.

I'd recommend using OpenAL, which I eventually did. It's a relatively straight-forward library and seems to have good cross-platform support. The other option is SDL_mixer, but OpenAL seemed easier to get installed on Windows (probably not by much though). So basically if QSound::play doesn't do what you want then the standard Qt API won't work for you.


Another important note, don't bother trying to fix the Qt sound api using a separate thread. It won't work. Phonon at least requires to be instantiated and called in the main thread.

查看更多
戒情不戒烟
3楼-- · 2019-01-25 23:44

http://doc.qt.nokia.com/latest/qsound.html

Qt provides the most commonly required audio operation in GUI applications: asynchronously playing a sound file. This is most easily accomplished using the static play() function:

 QSound::play("mysounds/bells.wav");

It seems like this is an asynchronous operation, so it shouldn't block your main thread.

查看更多
我想做一个坏孩纸
4楼-- · 2019-01-25 23:56

QMediaPlayer shouldn't block your thread.

#include <QtMultimedia/QMediaPlayer>

QMediaPlayer *player = new QMediaPlayer;
player->setMedia(QUrl::fromLocalFile("/path"));
player->setVolume(50);
player->play();
查看更多
看我几分像从前
5楼-- · 2019-01-26 00:06

I have been working with QT sound systems a lot, especially with the thread issues.

This solutions works for me:

  1. Convert any wav to mp3, because there is issues for playing wavs in qt 5.5.
  2. Add those mp3 files to your resources in QT (qrc).
  3. Use QMediaPlayer to play sounds.

Examples:

http://doc.qt.io/qt-5/qtmultimediawidgets-player-player-cpp.html

https://www.youtube.com/watch?v=DS7CDpIrwN4

查看更多
登录 后发表回答