The play function on audio and video elements is a promise

audio and video elements in HTML expose a play() function. This function returns a Promise<void>, so if you need to update some piece of UI in response to playing a piece of media and even show when it is loading, especially if you're not preloading the media, you can await play():

const handlePlayClick = async () => { const nextIsPaused = !isPaused; if (audioRef.current) { if (nextIsPaused) { audioRef.current.pause(); } else { try { setIsLoading(true); await audioRef.current.play(); setIsPaused(!isPaused); } catch { // Stay paused } setIsLoading(false); } } }

Doing this can also fix some cases where .play() and .pause() are inadvertently called in lock-step.

November 21, 2021 at 5:30 PM