Improved audio player

This commit is contained in:
Eduard Urbach 2018-03-11 05:10:32 +01:00
parent 5c9fe711c9
commit ecea644b9d

View File

@ -2,6 +2,10 @@ import { AnimeNotifier } from "../AnimeNotifier"
var audioContext: AudioContext
var audioNode: AudioBufferSourceNode
var playID = 0
var audioPlayer = document.getElementById("audio-player")
var audioPlayerPlay = document.getElementById("audio-player-play")
var audioPlayerPause = document.getElementById("audio-player-pause")
// Play audio file
export function playAudio(arn: AnimeNotifier, button: HTMLButtonElement) {
@ -9,31 +13,44 @@ export function playAudio(arn: AnimeNotifier, button: HTMLButtonElement) {
audioContext = new AudioContext()
}
playID++
// Stop existing audioNode
if(audioNode) {
audioNode.stop()
audioNode.disconnect()
audioNode = null
}
// Request
let request = new XMLHttpRequest()
request.open("GET", button.dataset.src, true)
request.responseType = "arraybuffer"
request.onload = () => {
audioContext.decodeAudioData(request.response, buffer => {
console.log("play")
audioNode = audioContext.createBufferSource()
audioNode.buffer = buffer
audioNode.connect(audioContext.destination)
audioNode.start(0)
audioNode.onended = () => {
document.getElementById("audio-player").classList.add("fade-out")
let currentPlayCount = playID
audioNode.onended = (event: MediaStreamErrorEvent) => {
if(currentPlayCount === playID) {
audioPlayer.classList.add("fade-out")
audioNode.disconnect()
}
}
}, console.error)
}
request.send()
// Show audio player
document.getElementById("audio-player").classList.remove("fade-out")
document.getElementById("audio-player-play").classList.add("fade-out")
document.getElementById("audio-player-pause").classList.remove("fade-out")
audioPlayer.classList.remove("fade-out")
audioPlayerPlay.classList.add("fade-out")
audioPlayerPause.classList.remove("fade-out")
}
// Pause audio
@ -44,8 +61,8 @@ export function pauseAudio(arn: AnimeNotifier, button: HTMLButtonElement) {
audioNode.playbackRate.setValueAtTime(0.0, 0)
document.getElementById("audio-player-play").classList.remove("fade-out")
document.getElementById("audio-player-pause").classList.add("fade-out")
audioPlayerPlay.classList.remove("fade-out")
audioPlayerPause.classList.add("fade-out")
}
// Resume audio
@ -56,6 +73,6 @@ export function resumeAudio(arn: AnimeNotifier, button: HTMLButtonElement) {
audioNode.playbackRate.setValueAtTime(1.0, 0)
document.getElementById("audio-player-play").classList.add("fade-out")
document.getElementById("audio-player-pause").classList.remove("fade-out")
audioPlayerPlay.classList.add("fade-out")
audioPlayerPause.classList.remove("fade-out")
}