Reputation: 151
i am working on a web application that will play a song from JS. The code that I have is:
const song = {
play: () => {
document.querySelector('body .audio').play();
},
pause: () => {
document.querySelector('body .audio').pause();
}
};
When i call song.play(), I get an error in the console:
Uncaught (in promise) DOMException
No more, just that. I have tried to search the internet but nothing can give me the answer. How can I solve this problem.
Update: I have done some more research, and it turns out that i can call the exact same script from the console and it works, but not from a script.
Upvotes: 2
Views: 6066
Reputation: 123
var promise = document.querySelector('audio').play();
if (promise !== undefined) {
promise.then(_ => {
// Autoplay started!
}).catch(error => {
// Autoplay was prevented.
// Show a "Play" button so that user can start playback.
});
}
Upvotes: 1