Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my Javascript audio not work after I refresh a page?

I have an audio object in my javascript and a call to the play function. It works fine when the I go to the page for the first time or go there through a link from one of my other pages, BUT when I'm on the page with the audio and just want to refresh the page I get audio errors,

Uncaught (in promise) DOMException

I have read a post about someone whose audio only works after they refresh it a few times (the opposite of my problem). And I've read about that error. But all I'm trying to do is refresh the page and have things work like they worked the first time.

console.log("playing test sound");
let test_sound = new Audio('/static/audio/to-the-point.mp3');
test_sound.play();

This works when I first go to the page, but then gives me that error when I refresh it and the audio doesn't work no matter how many more times I refresh... any ideas?

EDIT: upon playing around with it more, the times that the audio gets the error is very inconsistent upon refreshing. Sometimes, the refresh is fine other times it just gets an error. Once it gets the error though, subsequent refreshes also get it. Maybe it's my chrome browser or mac computer?

like image 394
Joshua Segal Avatar asked Oct 23 '25 17:10

Joshua Segal


1 Answers

Upon my own research and help from @Kokodoko it appears that you have to interact with your webpage before audio is allowed. This is why it worked for me when I came from another page, but failed when I refreshed.

The solution: make the user interact. Unfortunately, there is no true workaround for letting the audio play before the user has interacted. Forcing the user to interact in some way before the audio starts, is the only way to get the audio to work

like image 110
Joshua Segal Avatar answered Oct 25 '25 07:10

Joshua Segal