Last active
April 21, 2021 17:56
-
-
Save sayem314/8b7c76ee6e6f298b232d4c0ed21ace17 to your computer and use it in GitHub Desktop.
Progress hooks for react-native-track-player. This hooks updates when player is playing or seeking.
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 { useEffect, useState } from 'react'; | |
import TrackPlayer, { TrackPlayerEvents } from 'react-native-track-player'; | |
type Delay = number | null; | |
type TimerHandler = () => void; | |
/** | |
* Provides a declarative useInterval | |
* @param callback - Function that will be called every `delay` ms. | |
* @param delay - Number representing the delay in ms. Set to `null` to "pause" the interval. | |
*/ | |
const useInterval = (callback: TimerHandler, delay: Delay) => { | |
useEffect(() => { | |
if (delay !== null) { | |
const intervalId = setInterval(callback, delay); | |
return () => clearInterval(intervalId); | |
} | |
}, [delay]); | |
}; | |
/** | |
* Poll for track progress for the given interval (in milliseconds) | |
* @param {number} interval - ms interval | |
* @returns { progress: number, duration: number } | |
*/ | |
export const useTrackPlayerProgress = (interval = 1000) => { | |
const [playbackState, setPlaybackState] = useState(TrackPlayer.STATE_NONE); | |
const [state, setState] = useState({ position: 0, duration: 0 }); | |
const getProgress = async () => { | |
const [position, duration] = await Promise.all([TrackPlayer.getPosition(), TrackPlayer.getDuration()]); | |
setState({ position, duration }); | |
}; | |
useEffect(() => { | |
TrackPlayer.getState().then((currentPlaybackState) => { | |
// Update progress if the player is paused | |
if (currentPlaybackState === TrackPlayer.STATE_PAUSED) { | |
getProgress(); | |
} | |
setPlaybackState(currentPlaybackState); | |
}); | |
const sub = TrackPlayer.addEventListener(TrackPlayerEvents.PLAYBACK_STATE, (data) => { | |
setPlaybackState(data.state); | |
if (data.state === TrackPlayer.STATE_READY) { | |
getProgress(); | |
} | |
}); | |
return () => sub.remove(); | |
}, []); | |
useInterval(getProgress, playbackState === TrackPlayer.STATE_PLAYING ? interval : null); | |
return state; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment