owntone-server/web-src/src/audio.js

68 lines
1.6 KiB
JavaScript
Raw Normal View History

/**
* Audio handler object
* Taken from https://github.com/rainner/soma-fm-player (released under MIT licence)
*/
export default {
_audio: new Audio(),
_context: null,
_source: null,
_gain: null,
// Setup audio routing
setupAudio() {
2021-01-10 01:51:50 -05:00
const AudioContext = window.AudioContext || window.webkitAudioContext
this._context = new AudioContext()
this._source = this._context.createMediaElementSource(this._audio)
this._gain = this._context.createGain()
this._source.connect(this._gain)
this._gain.connect(this._context.destination)
this._audio.addEventListener('canplaythrough', (e) => {
this._audio.play()
})
this._audio.addEventListener('canplay', (e) => {
this._audio.play()
})
return this._audio
},
// Set audio volume
setVolume(volume) {
if (!this._gain) return
volume = parseFloat(volume) || 0.0
volume = volume < 0 ? 0 : volume
volume = volume > 1 ? 1 : volume
this._gain.gain.value = volume
},
// Play audio source url
playSource(source) {
this.stopAudio()
this._context.resume().then(() => {
2023-11-23 14:23:40 -05:00
this._audio.src = `${String(source || '')}?x=${Date.now()}`
this._audio.crossOrigin = 'anonymous'
this._audio.load()
})
},
// Stop playing audio
stopAudio() {
try {
this._audio.pause()
2022-02-19 01:05:59 -05:00
} catch (e) {
// Continue regardless of error
2022-02-19 01:05:59 -05:00
}
try {
this._audio.stop()
2022-02-19 01:05:59 -05:00
} catch (e) {
// Continue regardless of error
2022-02-19 01:05:59 -05:00
}
try {
this._audio.close()
2022-02-19 01:05:59 -05:00
} catch (e) {
// Continue regardless of error
2022-02-19 01:05:59 -05:00
}
}
}