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.
35 lines
993 B
35 lines
993 B
import { useEffect, useState } from 'react'
|
|
import { getSound } from 'requests/getSound'
|
|
import { readToken } from 'helpers'
|
|
|
|
export const useAudioPlayer = (id: number | string) => {
|
|
const [audio, setAudio] = useState<HTMLAudioElement>()
|
|
const [playing, setPlaying] = useState(false)
|
|
|
|
const toggle = () => {
|
|
setPlaying(!playing)
|
|
}
|
|
|
|
useEffect(() => {
|
|
getSound(id).then(({ asset }) => {
|
|
setAudio(new Audio(`${asset}?access_token=${readToken()}`))
|
|
})
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [id])
|
|
|
|
useEffect(() => {
|
|
if (!audio) return
|
|
playing ? audio.play() : audio.pause()
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [playing, audio])
|
|
|
|
useEffect(() => {
|
|
audio?.addEventListener('ended', () => setPlaying(false))
|
|
return () => {
|
|
audio?.removeEventListener('ended', () => setPlaying(false))
|
|
}
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [])
|
|
|
|
return { playing, toggle }
|
|
}
|
|
|