mirror of
https://github.com/scratchfoundation/scratch-audio.git
synced 2024-12-23 14:32:35 -05:00
54 lines
1.3 KiB
JavaScript
54 lines
1.3 KiB
JavaScript
var Tone = require('tone');
|
|
var log = require('./log');
|
|
|
|
function SoundPlayer () {
|
|
this.outputNode;
|
|
this.buffer; // a Tone.Buffer
|
|
this.bufferSource;
|
|
this.playbackRate = 1;
|
|
this.isPlaying = false;
|
|
}
|
|
SoundPlayer.prototype.connect = function (node) {
|
|
this.outputNode = node;
|
|
};
|
|
|
|
SoundPlayer.prototype.setBuffer = function (buffer) {
|
|
this.buffer = 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.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 () {
|
|
this.isPlaying = false;
|
|
callback();
|
|
};
|
|
};
|
|
|
|
module.exports = SoundPlayer;
|