soundengine.cpp 1.6 KB

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