Created
March 12, 2021 16:10
-
-
Save cwardzala/07cd60910d964781ccf9ef63319ff40e to your computer and use it in GitHub Desktop.
Basic React hook around `new Audio()`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
const useAudio = (initialSrc = null) => { | |
const [src, setSrc] = React.useState(initialSrc); | |
const [isPlaying, setIsPlaying] = React.useState(false); | |
const [progress, setProgress] = React.useState(0); | |
let audio = React.useRef(new Audio()); | |
React.useEffect(() => { | |
let currentAudio = audio.current; | |
let timeUpdate = () => { | |
if (!currentAudio?.currentTime || !currentAudio?.duration) { | |
return; | |
} | |
setProgress(Math.ceil((currentAudio.currentTime * 100) / currentAudio.duration)); | |
}; | |
let play = () => { | |
setIsPlaying(true); | |
}; | |
let pause = () => { | |
setIsPlaying(false); | |
}; | |
currentAudio.disableRemotePlayback = true; | |
currentAudio.addEventListener('timeupdate', timeUpdate, false); | |
currentAudio.addEventListener('play', play, true); | |
currentAudio.addEventListener('pause', pause, true); | |
// Prevent media keys from causing issues. | |
navigator.mediaSession.setActionHandler('play', () => {}); | |
navigator.mediaSession.setActionHandler('pause', () => {}); | |
return () => { | |
if (currentAudio && !currentAudio.paused) { | |
currentAudio.pause(); | |
} | |
currentAudio.removeEventListener('timeupdate', timeUpdate, false); | |
currentAudio.removeEventListener('play', play, true); | |
currentAudio.removeEventListener('pause', pause, true); | |
}; | |
}, []); | |
React.useEffect(() => { | |
let currentAudio = audio.current; | |
let handleSetAndPlay = async () => { | |
currentAudio.src = src; | |
setProgress(0); | |
await currentAudio.play(); | |
}; | |
if (audio?.current && src) { | |
if (!currentAudio.paused) currentAudio.pause(); | |
handleSetAndPlay(); | |
} | |
return () => { | |
currentAudio && currentAudio.pause(); | |
}; | |
}, [src]); | |
return { | |
audio: audio?.current, | |
progress, | |
isPlaying, | |
setSrc | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment