1 /* 2 * Copyright 2020 Google Inc. 3 * 4 * Use of this source code is governed by a BSD-style license that can be 5 * found in the LICENSE file. 6 */ 7 8 #include "include/core/SkData.h" 9 #include "modules/audioplayer/SkAudioPlayer.h" 10 11 #include <SFML/Audio.hpp> 12 13 namespace { 14 15 class SFMLAudioPlayer final : public SkAudioPlayer { 16 public: SFMLAudioPlayer(sk_sp<SkData> data)17 explicit SFMLAudioPlayer(sk_sp<SkData> data) 18 : fData(std::move(data)) 19 { 20 fMusic.openFromMemory(fData->data(), fData->size()); 21 } 22 23 private: onGetDuration() const24 double onGetDuration() const override { 25 return static_cast<double>(fMusic.getDuration().asSeconds()); 26 } 27 onGetTime() const28 double onGetTime() const override { 29 return static_cast<double>(fMusic.getPlayingOffset().asSeconds()); 30 } 31 onSetTime(double t)32 double onSetTime(double t) override { 33 fMusic.setPlayingOffset(sf::seconds(static_cast<float>(t))); 34 35 return this->onGetTime(); 36 } 37 onSetState(State state)38 State onSetState(State state) override { 39 switch (state) { 40 case State::kPlaying: fMusic.play(); break; 41 case State::kStopped: fMusic.stop(); break; 42 case State::kPaused : fMusic.pause(); break; 43 } 44 45 return state; 46 } 47 onSetRate(float r)48 float onSetRate(float r) override { 49 fMusic.setPitch(r); 50 return r; 51 } 52 onSetVolume(float v)53 float onSetVolume(float v) override { 54 fMusic.setVolume(v * 100); 55 return v; 56 } 57 58 const sk_sp<SkData> fData; 59 sf::Music fMusic; 60 }; 61 62 } // namespace 63 Make(sk_sp<SkData> src)64std::unique_ptr<SkAudioPlayer> SkAudioPlayer::Make(sk_sp<SkData> src) { 65 auto player = std::make_unique<SFMLAudioPlayer>(std::move(src)); 66 67 return player->duration() > 0 ? std::move(player) : nullptr; 68 } 69