简体   繁体   中英

How can I download and play audio clips without user interaction?

Is there a way programmatically to begin audio play before the user has interacted with the page?

With the following JavaScript:

console.log('Playing abc.');
XYZ.abc = new Audio('audio/abc.wav');
XYZ.abc.play();

I'm getting an error message,

Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.

When I click on the page, that goes away.

Is the standard UI pattern to request the user to click to start sound, or is there a loophole to do this programmatically?

Thanks,

So what the problem is that users don't usually expect audio to come from the website, so chrome requires your audio or video element to be muted by default. For the <audio> tag, you need to add the muted attribute, so -> <audio muted>

Respectively, the js element will have a .muted property. So, what you need is XYZ.abc.muted = true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM