57 lines
1.2 KiB
JavaScript
57 lines
1.2 KiB
JavaScript
/**
|
|
* AudioManager()
|
|
*
|
|
* A class to manage the audio stream.
|
|
*
|
|
* @param {string} src - The URL of the audio to play.
|
|
*/
|
|
class AudioManager {
|
|
constructor(src) {
|
|
this._muted = false;
|
|
|
|
// Create audio graph
|
|
this._context = new AudioContext();
|
|
this.audio = new Audio(src);
|
|
this._volume = this._context.createGain();
|
|
this._source = this._context.createMediaElementSource(this.audio);
|
|
|
|
let context = this._context;
|
|
let volume = this._volume;
|
|
let source = this._source;
|
|
|
|
source.connect(volume);
|
|
volume.connect(context.destination);
|
|
}
|
|
|
|
get context() {
|
|
return this._context;
|
|
}
|
|
|
|
get source() {
|
|
return this._source;
|
|
}
|
|
|
|
get muted() {
|
|
return this._muted;
|
|
}
|
|
|
|
addEventListener(...args) {
|
|
this.audio.addEventListener(...args);
|
|
}
|
|
|
|
mute() {
|
|
let context = this._context;
|
|
let volume = this._volume;
|
|
|
|
if (this._muted) {
|
|
volume.gain.setValueAtTime(1, context.currentTime);
|
|
} else {
|
|
volume.gain.setValueAtTime(0, context.currentTime);
|
|
}
|
|
|
|
this._muted = !this._muted;
|
|
}
|
|
}
|
|
|
|
export default AudioManager;
|