Audio playing in web game
To play an audio in web page is "easy".
const beep = new Audio('./beep.mp3');
beep.play();
This code loads the "beep.mp3" and plays it. However, if you run it in your Chrome you will hear nothing.
In the console you'll see the following error:
DOMException: play() failed because the user didn't interact with the document first. https://goo.gl/xX8pDD
Following the link in the error you'll see it's related to the Media Autoplay Policy which saves you from annoying autoplayed audio/video like those in ads.
Chrome's autoplay policies are simple:
Muted autoplay is always allowed.
Autoplay with sound is allowed if:
User has interacted with the domain (click, tap, etc.).
On desktop, the user's Media Engagement Index threshold has been crossed, meaning the user has previously played video with sound.
The user has added the site to their home screen on mobile or installed the PWA on desktop.
Top frames can delegate autoplay permission to their iframes to allow autoplay with sound.
The first rule means that you can always autoplay a muted video!
The rule 2.2 can be the solution -- just let the user click or tap the screen to unblock audio.
const beep = new Audio('./beep.mp3');
let audioUnblocked = false;
document.addEventListener('click', () => {
audioUnblocked = true;
});
function playBeep() {
if (!audioUnblocked) return;
beep.currentTime = 0;
beep.play();
}
Note that if two play of the same audio overlaps, the 2nd one won't take effect by default. So we added beep.currentTime = 0 to reset the audio to the beginning so that it can be played.
发表评论 (审核通过后显示评论):