sound.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include "sound.h"
  2. #include "miniaudio_backend.h"
  3. #include <QCryptographicHash>
  4. #include <QDebug>
  5. #include <QFileInfo>
  6. #include <qcryptographichash.h>
  7. #include <qfileinfo.h>
  8. #include <qglobal.h>
  9. #include <qobject.h>
  10. #include <qstringview.h>
  11. #include <string>
  12. Sound::Sound(const std::string &file_path, MiniaudioBackend *backend)
  13. : QObject(nullptr), m_file_path(file_path), m_backend(backend),
  14. m_loaded(false), m_volume(Sound::DEFAULT_VOLUME) {
  15. QByteArray const hash = QCryptographicHash::hash(
  16. QByteArray::fromStdString(file_path), QCryptographicHash::Md5);
  17. m_track_id = "sound_" + QString(hash.toHex());
  18. QFileInfo const file_info(QString::fromStdString(m_file_path));
  19. if (!file_info.exists()) {
  20. qWarning() << "Sound: File does not exist:" << file_info.absoluteFilePath();
  21. return;
  22. }
  23. if (m_backend != nullptr) {
  24. m_loaded = m_backend->predecode(m_track_id, file_info.absoluteFilePath());
  25. if (m_loaded) {
  26. qDebug() << "Sound: Loaded" << file_info.absoluteFilePath();
  27. }
  28. }
  29. }
  30. Sound::~Sound() = default;
  31. void Sound::set_backend(MiniaudioBackend *backend) {
  32. if (m_backend == backend) {
  33. return;
  34. }
  35. m_backend = backend;
  36. if ((m_backend != nullptr) && !m_loaded) {
  37. QFileInfo const file_info(QString::fromStdString(m_file_path));
  38. if (file_info.exists()) {
  39. m_loaded = m_backend->predecode(m_track_id, file_info.absoluteFilePath());
  40. }
  41. }
  42. }
  43. auto Sound::is_loaded() const -> bool { return m_loaded.load(); }
  44. void Sound::play(float volume, bool loop) {
  45. if ((m_backend == nullptr) || !m_loaded) {
  46. qWarning() << "Sound: Cannot play - backend not available or not loaded";
  47. return;
  48. }
  49. m_volume = volume;
  50. m_backend->play_sound(m_track_id, volume, loop);
  51. qDebug() << "Sound: Playing" << QString::fromStdString(m_file_path)
  52. << "volume:" << volume << "loop:" << loop;
  53. }
  54. void Sound::stop() {}
  55. void Sound::set_volume(float volume) { m_volume = volume; }