2016-11-21 12:40:35 -05:00
|
|
|
var Tone = require('tone');
|
2016-11-21 15:57:34 -05:00
|
|
|
var log = require('./log');
|
2016-11-21 12:40:35 -05:00
|
|
|
|
2017-01-30 11:25:43 -05:00
|
|
|
function SoundPlayer () {
|
2017-02-02 14:49:17 -05:00
|
|
|
this.outputNode = null;
|
|
|
|
this.buffer = new Tone.Buffer();
|
|
|
|
this.bufferSource = null;
|
2016-11-21 12:40:35 -05:00
|
|
|
this.playbackRate = 1;
|
2017-01-30 18:12:52 -05:00
|
|
|
this.isPlaying = false;
|
2016-11-21 12:40:35 -05:00
|
|
|
}
|
2017-01-30 11:25:43 -05:00
|
|
|
SoundPlayer.prototype.connect = function (node) {
|
|
|
|
this.outputNode = node;
|
|
|
|
};
|
2016-11-21 12:40:35 -05:00
|
|
|
|
|
|
|
SoundPlayer.prototype.setBuffer = function (buffer) {
|
|
|
|
this.buffer = buffer;
|
|
|
|
};
|
|
|
|
|
|
|
|
SoundPlayer.prototype.setPlaybackRate = function (playbackRate) {
|
|
|
|
this.playbackRate = playbackRate;
|
2016-11-21 15:57:34 -05:00
|
|
|
if (this.bufferSource && this.bufferSource.playbackRate) {
|
|
|
|
this.bufferSource.playbackRate.value = this.playbackRate;
|
|
|
|
}
|
2016-11-21 12:40:35 -05:00
|
|
|
};
|
|
|
|
|
|
|
|
SoundPlayer.prototype.stop = function () {
|
2017-01-30 11:26:55 -05:00
|
|
|
if (this.bufferSource) {
|
2016-11-21 12:40:35 -05:00
|
|
|
this.bufferSource.stop();
|
|
|
|
}
|
2017-01-30 18:13:18 -05:00
|
|
|
this.isPlaying = false;
|
2016-11-21 12:40:35 -05:00
|
|
|
};
|
|
|
|
|
|
|
|
SoundPlayer.prototype.start = function () {
|
2016-11-21 15:57:34 -05:00
|
|
|
if (!this.buffer || !this.buffer.loaded) {
|
|
|
|
log.warn('tried to play a sound that was not loaded yet');
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2016-11-21 12:40:35 -05:00
|
|
|
this.bufferSource = new Tone.BufferSource(this.buffer.get());
|
|
|
|
this.bufferSource.playbackRate.value = this.playbackRate;
|
|
|
|
this.bufferSource.connect(this.outputNode);
|
|
|
|
this.bufferSource.start();
|
2017-01-30 18:13:18 -05:00
|
|
|
|
|
|
|
this.isPlaying = true;
|
2016-11-21 12:40:35 -05:00
|
|
|
};
|
|
|
|
|
2017-01-30 11:26:55 -05:00
|
|
|
SoundPlayer.prototype.finished = function () {
|
|
|
|
var storedContext = this;
|
|
|
|
return new Promise(function (resolve) {
|
|
|
|
storedContext.bufferSource.onended = function () {
|
2017-01-30 18:13:18 -05:00
|
|
|
this.isPlaying = false;
|
2017-01-30 11:26:55 -05:00
|
|
|
resolve();
|
|
|
|
};
|
|
|
|
});
|
2016-11-21 12:40:35 -05:00
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = SoundPlayer;
|