add isplaying property, cleanup

This commit is contained in:
Eric Rosenbaum 2016-11-21 15:57:34 -05:00
parent 897fd68c90
commit b5d513f2b2

View file

@ -1,10 +1,12 @@
var Tone = require('tone'); var Tone = require('tone');
var log = require('./log');
function SoundPlayer (outputNode) { function SoundPlayer (outputNode) {
this.outputNode = outputNode; this.outputNode = outputNode;
this.buffer; // a Tone.Buffer this.buffer; // a Tone.Buffer
this.bufferSource; this.bufferSource;
this.playbackRate = 1; this.playbackRate = 1;
this.isPlaying = false;
} }
SoundPlayer.prototype.setBuffer = function (buffer) { SoundPlayer.prototype.setBuffer = function (buffer) {
@ -13,25 +15,37 @@ SoundPlayer.prototype.setBuffer = function (buffer) {
SoundPlayer.prototype.setPlaybackRate = function (playbackRate) { SoundPlayer.prototype.setPlaybackRate = function (playbackRate) {
this.playbackRate = playbackRate; this.playbackRate = playbackRate;
if (this.bufferSource && this.bufferSource.playbackRate) {
this.bufferSource.playbackRate.value = this.playbackRate;
}
}; };
SoundPlayer.prototype.stop = function () { SoundPlayer.prototype.stop = function () {
if (this.bufferSource){ if (this.isPlaying){
this.bufferSource.stop(); this.bufferSource.stop();
} }
}; };
SoundPlayer.prototype.start = function () { 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.stop();
this.bufferSource = new Tone.BufferSource(this.buffer.get()); this.bufferSource = new Tone.BufferSource(this.buffer.get());
this.bufferSource.playbackRate.value = this.playbackRate; this.bufferSource.playbackRate.value = this.playbackRate;
this.bufferSource.connect(this.outputNode); this.bufferSource.connect(this.outputNode);
this.bufferSource.start(); this.bufferSource.start();
this.isPlaying = true;
}; };
SoundPlayer.prototype.onEnded = function (callback) { SoundPlayer.prototype.onEnded = function (callback) {
this.bufferSource.onended = function () {callback();}; this.bufferSource.onended = function () {
this.isPlaying = false;
callback();
};
}; };
module.exports = SoundPlayer; module.exports = SoundPlayer;