owntone-server/web-src/src/audio.js
chme 3b718ffb16 [web-src] Add option to stream audio from player web interface
The audio implementation is based on
https://github.com/rainner/soma-fm-player and makes use of the  HTML5
Web Audio Context API.
2019-02-14 12:19:29 +01:00

52 lines
1.3 KiB
JavaScript

/**
* Audio handler object
* Taken from https://github.com/rainner/soma-fm-player (released under MIT licence)
*/
export default {
_audio: new Audio(),
_context: new AudioContext(),
_source: null,
_gain: null,
_analyser: null,
// setup audio routing
setupAudio () {
this._source = this._context.createMediaElementSource(this._audio)
this._analyser = this._context.createAnalyser()
this._gain = this._context.createGain()
this._source.connect(this._gain)
this._source.connect(this._analyser)
this._gain.connect(this._context.destination)
this._audio.addEventListener('canplaythrough', 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._audio.src = String(source || '') + '?x=' + Date.now()
this._audio.crossOrigin = 'anonymous'
this._audio.load()
},
// stop playing audio
stopAudio () {
try { this._audio.pause() } catch (e) {}
try { this._audio.stop() } catch (e) {}
try { this._audio.close() } catch (e) {}
}
}