How to prevent "The play() request was interrupted by a call to pause()" error?
I made a website where if the user clicks, it plays a sound. To prevent the sound from overlapping, I had to add the code:
n.pause();
n.currentTime = 0;
n.play();
But that causes the error:
The play() request was interrupted by a call to pause()
To come up each time the sound event is triggered right after another trigger. The sounds still plays fine, but I want to prevent this error message constantly popping up. Any ideas?
I have encountered this issue recently as well - this could be a race condition between play()
and pause()
. It looks like there is a reference to this issue, or something related here.
As @Patrick points out, pause
does not return a promise (or anything), so the above solution won't work. While MDN does not have docs on pause()
, in the WC3 draft for Media Elements, it says:
media.pause()
Sets the paused attribute to true, loading the media resource if necessary.
So one might also check the paused
attribute in their timeout callback.
Based on this great SO answer, here's a way you can check if the video is (or isn't) truly playing, so you can safely trigger a play() without the error.
var isPlaying = video.currentTime > 0 && !video.paused && !video.ended
&& video.readyState > video.HAVE_CURRENT_DATA;
if (!isPlaying) {
video.play();
}
Otherwise, @Patrick's answer should work.
After hours of seaching and working, i found perfect solution.
// Initializing values
var isPlaying = true;
// On video playing toggle values
video.onplaying = function() {
isPlaying = true;
};
// On video pause toggle values
video.onpause = function() {
isPlaying = false;
};
// Play video function
async function playVid() {
if (video.paused && !isPlaying) {
return video.play();
}
}
// Pause video function
function pauseVid() {
if (!video.paused && isPlaying) {
video.pause();
}
}
After that, you can toggle play/pause as fast as you can, it will work properly.
I have hit this issue, and have a case where I needed to hit pause() then play() but when using pause().then() I get undefined.
I found that if I started play 150ms after pause it resolved the issue. (Hopefully Google fixes soon)
playerMP3.volume = 0;
playerMP3.pause();
//Avoid the Promise Error
setTimeout(function () {
playerMP3.play();
}, 150);