Sandbox demo of my problem: https://codesandbox.io/s/jolly-fermat-j23w9
I'm trying to implement a feature on my React site where a user clicks an element, and the audio plays.
On desktop, this is working fine. But on iOS devices, I am encountering an "Unhandled Rejection (NotAllowedError)". This error usually is caused by autoplaying media on iOS devices. However, in this case, the user must click the element to start the audio, so this error should not be happening.
My suspicion is that because the component rerenders on state change, React doesn't know that the user had to interact with the site in order to trigger the audio.
Here is the basic code:
// audio playing function, found on this stackoverflow question:
// https://stackoverflow.com/questions/47686345/playing-sound-in-reactjs
const useAudio = url => {
const [audio] = useState(new Audio(url));
const [playing, setPlaying] = useState(false);
const toggle = () => setPlaying(!playing);
useEffect(() => {
playing ? audio.play() : audio.pause();
}, [playing]);
return [playing, toggle];
};
// url of audio is passed in as prop from App.js
const PlayAudio = ({ url }) => {
const [playing, toggle] = useAudio(url);
return (
<>
<PlayButton onClick={toggle}>{playing ? "Pause" : "Play"}</PlayButton>
</>
);
};
Tested on an iPhone using Safari, Chrome, and Firefox browsers.
Again, a full working demonstration can be found here, and you need to check on an iOS device to see the error: https://codesandbox.io/s/jolly-fermat-j23w9
Any help is appreciated.
Created example with yours code but another approach:
<audio ref....>