soundengine.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include "include/soundengine.h"
  2. AsyncSound::AsyncSound(QString path) {
  3. player = new QMediaPlayer();
  4. player->setMedia(QUrl(path));
  5. player->setVolume(50);
  6. player->play();
  7. connect(player, &QMediaPlayer::stateChanged, this, &AsyncSound::onStateChanged);
  8. }
  9. AsyncSound::~AsyncSound() {
  10. delete player;
  11. }
  12. QMediaPlayer* AsyncSound::operator->() const
  13. {
  14. return player;
  15. }
  16. void AsyncSound::onStateChanged(const QMediaPlayer::State &state)
  17. {
  18. if (state == QMediaPlayer::StoppedState)
  19. emit finished(shared_from_this());
  20. }
  21. QMediaPlayer& SoundEngine::player() const {
  22. return *player_;
  23. }
  24. QMediaPlaylist& SoundEngine::playlist() const {
  25. return *playlist_;
  26. }
  27. std::shared_ptr<AsyncSound> SoundEngine::playAsync(QString path) {
  28. auto sound_ptr = std::make_shared<AsyncSound>(path);
  29. if (!sound_ptr)
  30. return sound_ptr;
  31. connect(&(*sound_ptr), &AsyncSound::finished, this, &SoundEngine::onAsyncSoundFinished);
  32. async_sounds.insert(sound_ptr);
  33. return sound_ptr;
  34. }
  35. SoundEngine::SoundEngine(QObject *parent) : QObject(parent) {
  36. player_ = new QMediaPlayer();
  37. playlist_ = new QMediaPlaylist(player_);
  38. player_->setPlaylist(playlist_);
  39. playlist_->setPlaybackMode(QMediaPlaylist::Loop);
  40. player_->setVolume(50);
  41. }
  42. SoundEngine::~SoundEngine() {
  43. player_->deleteLater();
  44. playlist_->deleteLater();
  45. }
  46. void SoundEngine::onAsyncSoundFinished(const std::shared_ptr<AsyncSound> &sound)
  47. {
  48. if (async_sounds.count(sound))
  49. async_sounds.erase(sound);
  50. }