Uncaught (in promise): The play() request was interrupted by a call to pause().
scene
When JavaScript calls Audio to play the sound, the above error prompts often appear because of improper handling.
problem analysis
Immediately after calling Audio's play() method, it is interrupted by the subsequent call to pause() method. The error prompt clearly indicates that calling the play method returns a Promise object. Then there is a solution to the above problem: after the play() is successfully executed, play the audio, and then perform subsequent operations.
audio.play()
Write an example to test audio.play():
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Audio.play()</title>
</head>
<body>
<script>
(function (argument) {
// Audio file
var src = "./rank.mp3";
// Initialize Aduio
var audio = new Audio();
audio.src = src;
console.log(audio.play() instanceof Promise); // true
})();
</script>
</body>
</html>
Solution
All right, now we just need to make a few changes to the above example.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Audio.play()</title>
</head>
<body>
<script>
(function (argument) {
// Audio file
var src = "./rank.mp3";
// Initialize Aduio
var audio = new Audio();
var playPromise;
audio.src = src;
playPromise = audio.play();
if (playPromise) {
playPromise.then(() => {
// Audio Loading Successful
// Audio playback takes time
setTimeout(() => {
// Follow up operation
console.log("done.");
}, audio.duration * 1000); // audio.duration is the length of the audio in seconds.
}).catch((e) => {
// Audio loading failure
});
}
})();
</script>
</body>
</html>