You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
40 lines
970 B
40 lines
970 B
import {
|
|
SyntheticEvent,
|
|
useEffect,
|
|
useState,
|
|
useRef,
|
|
} from 'react'
|
|
import { readToken } from 'helpers'
|
|
|
|
export const useAudioPlayer = (asset: string) => {
|
|
const audio = useRef<HTMLAudioElement>(new Audio(''))
|
|
const [playing, setPlaying] = useState(false)
|
|
|
|
const toggle = (e: SyntheticEvent) => {
|
|
e.preventDefault()
|
|
e.stopPropagation()
|
|
if (audio.current.paused) {
|
|
audio.current.play()
|
|
setPlaying(true)
|
|
} else {
|
|
audio.current.pause()
|
|
setPlaying(false)
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
setPlaying(false)
|
|
audio.current?.pause()
|
|
audio.current = new Audio(`${asset}?access_token=${readToken()}`)
|
|
}, [asset])
|
|
|
|
useEffect(() => {
|
|
audio.current?.addEventListener('ended', () => audio.current.pause())
|
|
return () => {
|
|
audio.current?.removeEventListener('ended', () => audio.current.pause())
|
|
}
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [])
|
|
|
|
return { playing, toggle }
|
|
}
|
|
|