2019-02-14 12:19:29 +01:00
|
|
|
/**
|
|
|
|
* Audio handler object
|
2023-12-06 20:24:55 +01:00
|
|
|
* Inspired by https://github.com/rainner/soma-fm-player
|
|
|
|
* (released under MIT licence)
|
2019-02-14 12:19:29 +01:00
|
|
|
*/
|
|
|
|
export default {
|
|
|
|
_audio: new Audio(),
|
2019-02-19 10:33:07 +01:00
|
|
|
_context: null,
|
2019-02-14 12:19:29 +01:00
|
|
|
|
2023-06-07 21:25:54 +02:00
|
|
|
// Setup audio routing
|
2022-02-19 06:39:14 +01:00
|
|
|
setupAudio() {
|
2023-12-06 20:24:55 +01:00
|
|
|
this._context = new (window.AudioContext || window.webkitAudioContext)()
|
|
|
|
const source = this._context.createMediaElementSource(this._audio)
|
|
|
|
source.connect(this._context.destination)
|
2022-02-19 06:39:14 +01:00
|
|
|
this._audio.addEventListener('canplaythrough', (e) => {
|
2019-02-14 12:19:29 +01:00
|
|
|
this._audio.play()
|
|
|
|
})
|
2022-02-19 06:39:14 +01:00
|
|
|
this._audio.addEventListener('canplay', (e) => {
|
2019-02-18 12:47:09 +01:00
|
|
|
this._audio.play()
|
|
|
|
})
|
2019-02-14 12:19:29 +01:00
|
|
|
return this._audio
|
|
|
|
},
|
|
|
|
|
2023-06-07 21:25:54 +02:00
|
|
|
// Set audio volume
|
2022-02-19 06:39:14 +01:00
|
|
|
setVolume(volume) {
|
2023-12-06 20:24:55 +01:00
|
|
|
if (this._audio) {
|
|
|
|
this._audio.volume = Math.min(1, Math.max(0, parseFloat(volume) || 0.0))
|
|
|
|
}
|
2019-02-14 12:19:29 +01:00
|
|
|
},
|
|
|
|
|
2023-06-07 21:25:54 +02:00
|
|
|
// Play audio source url
|
2022-02-19 06:39:14 +01:00
|
|
|
playSource(source) {
|
2019-02-14 12:19:29 +01:00
|
|
|
this.stopAudio()
|
2019-02-18 12:47:09 +01:00
|
|
|
this._context.resume().then(() => {
|
2023-11-23 20:23:40 +01:00
|
|
|
this._audio.src = `${String(source || '')}?x=${Date.now()}`
|
2019-02-18 12:47:09 +01:00
|
|
|
this._audio.crossOrigin = 'anonymous'
|
|
|
|
this._audio.load()
|
|
|
|
})
|
2019-02-14 12:19:29 +01:00
|
|
|
},
|
|
|
|
|
2023-06-07 21:25:54 +02:00
|
|
|
// Stop playing audio
|
2022-02-19 06:39:14 +01:00
|
|
|
stopAudio() {
|
|
|
|
try {
|
|
|
|
this._audio.pause()
|
2022-02-19 07:05:59 +01:00
|
|
|
} catch (e) {
|
2023-06-07 21:25:54 +02:00
|
|
|
// Continue regardless of error
|
2022-02-19 07:05:59 +01:00
|
|
|
}
|
2022-02-19 06:39:14 +01:00
|
|
|
try {
|
|
|
|
this._audio.stop()
|
2022-02-19 07:05:59 +01:00
|
|
|
} catch (e) {
|
2023-06-07 21:25:54 +02:00
|
|
|
// Continue regardless of error
|
2022-02-19 07:05:59 +01:00
|
|
|
}
|
2022-02-19 06:39:14 +01:00
|
|
|
try {
|
|
|
|
this._audio.close()
|
2022-02-19 07:05:59 +01:00
|
|
|
} catch (e) {
|
2023-06-07 21:25:54 +02:00
|
|
|
// Continue regardless of error
|
2022-02-19 07:05:59 +01:00
|
|
|
}
|
2019-02-14 12:19:29 +01:00
|
|
|
}
|
|
|
|
}
|