I am working on the Asp.Net MVC Web application. I am calling one javascript method using SignalR, and in this method, I am trying to play sound from some backend event, but it doesn't play if I am not on the same browser tab or my browser is minimized just like the youtube video ( you click on the youtube video link, it will not play until and unless you bring that screen foreground once).
<audio id="audioId" autoplay loop>
<source src="test.mp3" type="audio/mpeg">
</audio>
code to play the audio audioId.play();
It works fine if I am on the screen, but not if the screen is minimized or in the background.
You can do it without html markup.
But keep in mind that audio file need to be load before the user minimize the screen. And the user have to interact (scroll, click, or any touch or click event) with document before minimize (as any autoplay feature).
Or you gonna have following error: Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first
Take a look to google about autoplay: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
So if you try something like that it's will not work:
$(element).on('your-event', function(){
var audio = new Audio('https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3');
audio.play();
}
But this way should work
var audio = new Audio('https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3');
$(element).on('your-event', function(){
audio.play();
}
Here is a working example on codepen: https://codepen.io/zecka/pen/VwjxGbE