crypto-slots
Version:
A minimal test server is provided, see server
47 lines (37 loc) • 1.35 kB
JavaScript
export default class SlotSound {
constructor(src, context) {
if (!src) throw Error('path to file needed')
if (!context) this.audioContext = new AudioContext()
else this.audioContext = context
this.src = src
this.gainNode = this.audioContext.createGain();
(async() => {
const response = await fetch(this.src);
const audioData = await response.arrayBuffer();
this.audioContext.decodeAudioData(audioData, buffer => {
this.buffer = buffer;
// preload rigntone (get rid of the delay on first play)
this.source = this.audioContext.createBufferSource()
this.source.connect(this.gainNode)
this.gainNode.connect(this.audioContext.destination)
// this.source.buffer = this.buffer;
})
})()
this.playing = false;
}
play() {
if (this.playing) return;
this.playing = true;
this.source = this.audioContext.createBufferSource()
this.source.connect(this.gainNode)
this.gainNode.connect(this.audioContext.destination)
this.source.buffer = this.buffer;
this.source.loop = this.loop;
this.source.start(this.startTime);
}
stop() {
if (!this.playing) return;
this.playing = false;
this.source.stop(this.stopTime);
}
}