Created
August 15, 2022 07:28
-
-
Save degitgitagitya/114f372323f8cd8b90ef163a25d769e8 to your computer and use it in GitHub Desktop.
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 usePlayerStore from '../hooks/use-player-store/use-player-store'; | |
import { useCallback } from 'react'; | |
export function UsePlayer() { | |
const { audio, setAudio, state, setState, updateTime, updateDuration } = | |
usePlayerStore(); | |
const preLoad = useCallback( | |
(url: string) => { | |
const audio = new Audio(url); | |
audio.ontimeupdate = (event) => { | |
const target = event.target as HTMLAudioElement; | |
updateTime(target.currentTime); | |
}; | |
audio.ondurationchange = (event) => { | |
const target = event.target as HTMLAudioElement; | |
updateDuration(target.duration); | |
}; | |
setAudio(audio); | |
}, | |
[setAudio, updateTime, updateDuration] | |
); | |
const play = useCallback(() => { | |
if (audio) { | |
console.log('play'); | |
audio.play(); | |
setState({ | |
...state, | |
paused: false, | |
playing: true, | |
}); | |
} | |
}, [audio, state, setState]); | |
const pause = useCallback(() => { | |
if (audio) { | |
console.log('pause'); | |
audio.pause(); | |
setState({ | |
...state, | |
paused: true, | |
playing: false, | |
}); | |
} | |
}, [audio, state, setState]); | |
const mute = useCallback(() => { | |
if (audio) { | |
console.log('mute'); | |
audio.muted = true; | |
setState({ | |
...state, | |
muted: true, | |
}); | |
} | |
}, [audio, state, setState]); | |
const unmute = useCallback(() => { | |
if (audio) { | |
console.log('unmute'); | |
audio.muted = false; | |
setState({ | |
...state, | |
muted: false, | |
}); | |
} | |
}, [audio, state, setState]); | |
const volume = useCallback( | |
(volume: number) => { | |
if (audio) { | |
console.log('volume'); | |
volume = Math.min(1, Math.max(0, volume)); | |
audio.volume = volume; | |
setState({ | |
...state, | |
volume, | |
}); | |
} | |
}, | |
[audio, state, setState] | |
); | |
const seek = useCallback( | |
(time: number) => { | |
if (audio && state && state.duration) { | |
console.log('seek'); | |
time = Math.min(state.duration, Math.max(0, time)); | |
audio.currentTime = time; | |
setState({ | |
...state, | |
time, | |
}); | |
} | |
}, | |
[audio, state, setState] | |
); | |
return { preLoad, play, pause, mute, unmute, volume, seek }; | |
} | |
export default UsePlayer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment