audio.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /* audio.cpp - audio player
  2. * Copyright (C) 2017 caryoscelus
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. #include <QMediaPlayer>
  18. #include <QFileInfo>
  19. #include <core/node/abstract_node.h>
  20. #include <core/document.h>
  21. #include <util/strings.h>
  22. #include "audio.h"
  23. namespace rainynite::studio {
  24. AudioPlayer::AudioPlayer() :
  25. player(make_unique<QMediaPlayer>())
  26. {}
  27. AudioPlayer::~AudioPlayer() = default;
  28. void AudioPlayer::set_context(shared_ptr<EditorContext> context) {
  29. ContextListener::set_context(context);
  30. if (auto doc = get_core_context()->get_document()) {
  31. auto audio_node = dynamic_pointer_cast<core::AbstractNode>(doc->get_property("soundtrack"));
  32. if (audio_node == nullptr)
  33. return;
  34. auto maybe_fname = audio_node->get_property_value<string>("file_path", get_core_context());
  35. if (!maybe_fname)
  36. return;
  37. auto fname = *maybe_fname;
  38. if (fname == cached_file)
  39. return;
  40. using util::str;
  41. player->setMedia(QUrl::fromUserInput(
  42. str(fname),
  43. QFileInfo(str(get_context()->get_file_name())).absolutePath()
  44. ));
  45. cached_file = fname;
  46. connect_boost(
  47. get_context()->changed_time(),
  48. [this](auto time) {
  49. update(std::move(time));
  50. }
  51. );
  52. connect_boost(
  53. get_context()->playback_change,
  54. [this](bool playing) {
  55. is_playing = playing;
  56. if (playing)
  57. player->play();
  58. else
  59. player->pause();
  60. }
  61. );
  62. }
  63. }
  64. void AudioPlayer::update(core::Time time) {
  65. player->setPosition(time.get_seconds()*1000);
  66. // TODO: play one frame sample even when not playing
  67. if (is_playing)
  68. player->play();
  69. }
  70. } // namespace rainynite::studio