export default class SoundPlayer {
constructor() {
this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
this.audioBuffer = null;
this.sourceNode = null;
this.gainNode = this.audioContext.createGain();
this.isPlaying = false;
this.isEnd = false;
this.trackTime = 0;
this.past = 0;
this.duration=41.3;
this.time=0;
}
async load(url) {
const response = await fetch(url);
const arrayBuffer = await response.arrayBuffer();
this.audioBuffer = await this.audioContext.decodeAudioData(arrayBuffer);
this.duration = this.audioBuffer.duration;
console.log("duration " + this.audioBuffer.duration)
}
play() {
console.log("play - ",this.isPlaying);
if (!this.audioBuffer) {
console.warn('Audio buffer is not loaded');
return;
}
this.sourceNode = this.audioContext.createBufferSource();
this.sourceNode.buffer = this.audioBuffer;
this.sourceNode.connect(this.gainNode).connect(this.audioContext.destination);
this.past = this.audioContext.currentTime;
this.sourceNode.start(0, this.trackTime);
this.isPlaying = true;
this.sourceNode.onended = () => {
console.log("end")
this.isPlaying = false;
};
}
stop() {
if(this.sourceNode){
this.sourceNode.stop();
}
this.isPlaying = false;
}
setTime(seconds) {
console.log("setTime " + seconds);
this.stop();
this.trackTime = seconds;
this.play();
}
setVolume(volume) {
this.gainNode.gain.value = volume*0.1;
}
update(){
if(!this.isPlaying)return;
this.trackTime+=(this.audioContext.currentTime-this.past);
this.past = this.audioContext.currentTime
this.time = this.trackTime;
if(this.time>=this.duration){
console.log("end");
this.isEnd = true;
}
}
reset(){
this.stop();
this.setTime(0);
this.time=0;
}
}