From b5d513f2b26c5407f2d9611cf0e745b71c035c07 Mon Sep 17 00:00:00 2001 From: Eric Rosenbaum Date: Mon, 21 Nov 2016 15:57:34 -0500 Subject: [PATCH] add isplaying property, cleanup --- src/SoundPlayer.js | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/SoundPlayer.js b/src/SoundPlayer.js index ac24e5c..0783efe 100644 --- a/src/SoundPlayer.js +++ b/src/SoundPlayer.js @@ -1,10 +1,12 @@ var Tone = require('tone'); +var log = require('./log'); function SoundPlayer (outputNode) { this.outputNode = outputNode; this.buffer; // a Tone.Buffer this.bufferSource; this.playbackRate = 1; + this.isPlaying = false; } SoundPlayer.prototype.setBuffer = function (buffer) { @@ -13,25 +15,37 @@ SoundPlayer.prototype.setBuffer = function (buffer) { SoundPlayer.prototype.setPlaybackRate = function (playbackRate) { this.playbackRate = playbackRate; + if (this.bufferSource && this.bufferSource.playbackRate) { + this.bufferSource.playbackRate.value = this.playbackRate; + } }; SoundPlayer.prototype.stop = function () { - if (this.bufferSource){ + if (this.isPlaying){ this.bufferSource.stop(); } }; SoundPlayer.prototype.start = function () { + if (!this.buffer || !this.buffer.loaded) { + log.warn('tried to play a sound that was not loaded yet'); + return; + } + this.stop(); this.bufferSource = new Tone.BufferSource(this.buffer.get()); this.bufferSource.playbackRate.value = this.playbackRate; this.bufferSource.connect(this.outputNode); this.bufferSource.start(); + this.isPlaying = true; }; SoundPlayer.prototype.onEnded = function (callback) { - this.bufferSource.onended = function () {callback();}; + this.bufferSource.onended = function () { + this.isPlaying = false; + callback(); + }; }; module.exports = SoundPlayer;