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/SkCanvas.h" 9 #include "include/core/SkData.h" 10 #include "modules/audioplayer/SkAudioPlayer.h" 11 #include "samplecode/Sample.h" 12 #include "src/core/SkUtils.h" 13 #include "tools/Resources.h" 14 15 class AudioView : public Sample { 16 std::unique_ptr<SkAudioPlayer> fPlayer; 17 SkRect fBar; 18 19 public: AudioView()20 AudioView() {} 21 22 protected: name()23 SkString name() override { return SkString("Audio"); } 24 onOnceBeforeDraw()25 void onOnceBeforeDraw() override { 26 auto data = SkData::MakeFromFileName("/Users/reed/skia/mp3/scott-joplin-peacherine-rag.mp3"); 27 if (data) { 28 fPlayer = SkAudioPlayer::Make(data); 29 30 SkDebugf("make: dur:%g time%g state:%d", 31 fPlayer->duration(), 32 fPlayer->time(), 33 (int)fPlayer->state()); 34 } 35 36 fBar = { 10, 10, 510, 30 }; 37 } 38 onDrawContent(SkCanvas * canvas)39 void onDrawContent(SkCanvas* canvas) override { 40 if (!fPlayer) { 41 return; 42 } 43 44 SkPaint p; 45 p.setColor(0xFFCCCCCC); 46 canvas->drawRect(fBar, p); 47 48 p.setColor(fPlayer->isPlaying() ? SK_ColorBLUE : 0xFF8888FF); 49 SkRect r = fBar; 50 r.fRight = r.fLeft + (float)fPlayer->normalizedTime() * r.width(); 51 canvas->drawRect(r, p); 52 } 53 onChar(SkUnichar c)54 bool onChar(SkUnichar c) override { 55 if (c == ' ') { 56 switch (fPlayer->state()) { 57 case SkAudioPlayer::State::kPlaying: fPlayer->pause(); break; 58 case SkAudioPlayer::State::kPaused: fPlayer->play(); break; 59 case SkAudioPlayer::State::kStopped: fPlayer->play(); break; 60 } 61 return true; 62 } 63 return this->INHERITED::onChar(c); 64 } 65 onFindClickHandler(SkScalar x,SkScalar y,skui::ModifierKey)66 Click* onFindClickHandler(SkScalar x, SkScalar y, skui::ModifierKey) override { 67 if (fPlayer && fBar.contains(x, y)) { 68 bool wasPlaying = fPlayer->isPlaying(); 69 if (wasPlaying) { 70 fPlayer->pause(); 71 } 72 return new Click([this, wasPlaying](Click* click) { 73 if (fBar.contains(click->fCurr.fX, click->fCurr.fY)) { 74 fPlayer->setNormalizedTime((click->fCurr.fX - fBar.fLeft) / fBar.width()); 75 } 76 77 if (click->fState == skui::InputState::kUp) { 78 if (wasPlaying) { 79 fPlayer->play(); 80 } 81 } 82 return true; 83 }); 84 } 85 return nullptr; 86 } 87 onAnimate(double)88 bool onAnimate(double /*nanos*/) override { 89 return true; 90 } 91 92 private: 93 using INHERITED = Sample; 94 }; 95 DEF_SAMPLE( return new AudioView; ) 96