Created
January 1, 2024 10:07
-
-
Save Karthik-B-06/af4cc107cadcfa6c6a5f3e729231b6b8 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
const AudioPlayer = (props: AudioPlayerProps) => { | |
const { audioSrc } = props; | |
const [isPlaying, setIsPlaying] = useState(false); | |
const [isSoundLoading, setSoundLoadStatus] = useState(true); | |
const { position, duration } = useProgress(); | |
const currentPosition = useDerivedValue(() => Math.round(position)); | |
const totalDuration = useDerivedValue(() => Math.round(duration)); | |
const resetPlayer = () => { | |
TrackPlayer.seekTo(0).then(() => { | |
setIsPlaying(false); | |
TrackPlayer.pause(); | |
}); | |
}; | |
const pauseAudio = () => { | |
TrackPlayer.pause(); | |
}; | |
const manualSeekTo = (manualSeekPosition: number) => { | |
TrackPlayer.seekTo(manualSeekPosition).then(() => { | |
TrackPlayer.play(); | |
}); | |
}; | |
useAnimatedReaction( | |
() => currentPosition.value, | |
(next, _prev) => { | |
if (next === totalDuration.value && next !== 0) { | |
runOnJS(resetPlayer)(); | |
} | |
}, | |
); | |
const togglePlayback = () => { | |
if (isPlaying) { | |
TrackPlayer.pause(); | |
} else { | |
TrackPlayer.add([{ url: audioSrc }]) | |
.then(() => { | |
TrackPlayer.play(); | |
}) | |
.catch(() => {}); | |
} | |
setIsPlaying(!isPlaying); | |
}; | |
useEffect(() => { | |
const setPlayer = async () => { | |
TrackPlayer.getPlaybackState() | |
.then(() => { | |
setSoundLoadStatus(false); | |
}) | |
.catch(() => { | |
// When player has been already setup | |
TrackPlayer.setupPlayer() | |
.then(() => { | |
setSoundLoadStatus(false); | |
}) | |
.catch(() => {}); | |
}); | |
}; | |
setPlayer(); | |
return () => { | |
TrackPlayer.seekTo(0).then(() => TrackPlayer.pause()); | |
setIsPlaying(false); | |
}; | |
}, []); | |
return ( | |
<View style={tailwind.style("flex flex-row items-center flex-1")}> | |
<Pressable | |
disabled={isSoundLoading} | |
hitSlop={10} | |
onPressIn={togglePlayback} | |
> | |
{isSoundLoading ? ( | |
<Animated.View entering={FadeIn} exiting={FadeOut}> | |
<Spinner size={13} /> | |
</Animated.View> | |
) : isPlaying ? ( | |
<Animated.View | |
style={tailwind.style("pl-0.5 pr-0.5")} | |
entering={FadeIn} | |
exiting={FadeOut} | |
> | |
<Icon icon={<PauseIcon />} size={13} /> | |
</Animated.View> | |
) : ( | |
<Animated.View | |
style={tailwind.style("pl-0.5 pr-0.5")} | |
entering={FadeIn} | |
exiting={FadeOut} | |
> | |
<Icon icon={<PlayIcon />} size={13} /> | |
</Animated.View> | |
)} | |
</Pressable> | |
<Slider | |
{...{ manualSeekTo, currentPosition, totalDuration, pauseAudio }} | |
/> | |
</View> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment