Reputation: 1837
Hello I am getting an exception when playing audio in Chrome.
Here is my function to play the audio
$(document).ready(function ()
{
generateAlarm();
});
function generateAlarm()
{
alarm_1 = new Audio();
alarm_1.src = '/Content/assets/sounds/alarm_1.mp3';
const playPromise = alarm_1.play();
if (playPromise !== null)
{
playPromise.catch(() => {
const btn = $('#playAlarm');
btn.click();
});
}
}
document.getElementById('playAlarm').addEventListener("click", handlePlayButton, false);
function handlePlayButton()
{
if (alarm_1.paused) {
generateAlarm();
}
else {
alarm_1.pause();
}
}
Can anyone tell me what is wrong with the above code? Thank you in advance.
Upvotes: 1
Views: 296
Reputation: 1837
The only solution i could find so far was to change the chrome autoplay policies like this:
chrome://flags/#autoplay-policy
and set it to
No user gesture is required
i don't if it is the right way to solve the problem, but i am not getting anymore exception. I would appreciate if anyone has a better idea.
Upvotes: 1
Reputation: 11745
Autoplaying audio is no longer allowed because it's obnoxious and is frequently abused. You have to wait for the user to interact with the page first. You can check out this guide by google on how to use the new AudioContext
api: https://developers.google.com/web/updates/2018/11/web-audio-autoplay
Upvotes: 2