Skip to content

Commit

Permalink
player handlers
Browse files Browse the repository at this point in the history
  • Loading branch information
Hendrixer committed Dec 15, 2021
1 parent 63355af commit cbb9d8d
Showing 1 changed file with 56 additions and 2 deletions.
58 changes: 56 additions & 2 deletions components/player.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,11 @@ const Player = ({ songs, activeSong }) => {
const [playing, setPlaying] = useState(true)
const [index, setIndex] = useState(0)
const [seek, setSeek] = useState(0.0)
const [isSeeking, setIsSeeking] = useState(false)
const [repeat, setRepeat] = useState(false)
const [shuffle, setShuffle] = useState(false)
const [duration, setDuration] = useState(0.0)
const soundRef = useRef(null)

const setPlayState = (value) => {
setPlaying(value)
Expand All @@ -42,10 +44,56 @@ const Player = ({ songs, activeSong }) => {
setRepeat((state) => !state)
}

const prevSong = () => {
setIndex((state) => {
return state ? state - 1 : songs.length - 1
})
}

const nextSong = () => {
setIndex((state) => {
if (shuffle) {
const next = Math.floor(Math.random() * songs.length)

if (next === state) {
return nextSong()
}
return next
}

return state === songs.length - 1 ? 0 : state + 1
})
}

const onEnd = () => {
if (repeat) {
setSeek(0)
soundRef.current.seek(0)
} else {
nextSong()
}
}

const onLoad = () => {
const songDuration = soundRef.current.duration()
setDuration(songDuration)
}

const onSeek = (e) => {
setSeek(parseFloat(e[0]))
soundRef.current.seek(e[0])
}

return (
<Box>
<Box>
<ReactHowler playing={playing} src={activeSong?.url} />
<ReactHowler
playing={playing}
src={activeSong?.url}
ref={soundRef}
onLoad={onLoad}
onEnd={onEnd}
/>
</Box>
<Center color="gray.600">
<ButtonGroup>
Expand All @@ -64,6 +112,7 @@ const Player = ({ songs, activeSong }) => {
aria-label="skip"
fontSize="24px"
icon={<MdSkipPrevious />}
onClick={prevSong}
/>
{playing ? (
<IconButton
Expand Down Expand Up @@ -93,6 +142,7 @@ const Player = ({ songs, activeSong }) => {
aria-label="next"
fontSize="24px"
icon={<MdSkipNext />}
onClick={nextSong}
/>
<IconButton
outline="none"
Expand All @@ -116,8 +166,12 @@ const Player = ({ songs, activeSong }) => {
aria-label={['min', 'max']}
step={0.1}
min={0}
max={321}
id="player-range"
max={duration ? duration.toFixed(2) : 0}
onChange={onSeek}
value={[seek]}
onChangeStart={() => setIsSeeking(true)}
onChangeEnd={() => setIsSeeking(false)}
>
<RangeSliderTrack bg="gray.800">
<RangeSliderFilledTrack bg="gray.600" />
Expand Down

0 comments on commit cbb9d8d

Please sign in to comment.