Django/html mp3 autoplay
I've got django application, and one view, that checks some data, and passess "play" variable to the template. If play is true - short mp3 "bing" should be played, else, it is not played. The page reloads every 10 seconds, to call view, checks if 'play' changed, and make sound possibly. The problem is, that just after first page load, nothing is autoplayed. I need to click play button on html player one time, and after that, everything works perfectly. But without this first "manual play", it is not working. Any ideas? The django template code is as follows.
<html>
<head>
<script>
window.onload = function() {
var context = new AudioContext();
}
function autoRefresh() {
window.location = window.location.href;
}
setInterval('autoRefresh()', 10000);
</script>
</head>
<body>
{%if play%}
<audio autoplay controls id="music" >
<source src="{%static 'app1/stat1/d.mp3'%}" type="audio/mpeg">
</audio>
{%endif%}
</body>
</html>
Not all browsers allow autoplaying, or at least not immediately. The documentation on the autoplay
attribute [mdn-doc] says:
Autoplay availability
As a general rule, you can assume that media will be allowed to autoplay only if at least one of the following is true:
- The audio is muted or its volume is set to 0
- The user has interacted with the site (by clicking, tapping, pressing keys, etc.)
- If the site has been allowlisted; this may happen either automatically if the browser determines that the user engages with media frequently, or manually through preferences or other user interface features
- If the
autoplay
Permissions Policy [mdn-doc] is used to grant autoplay support to an<iframe>
and its document.
In your case, probably the second condition holds. You thus should look what permissions you allowed by your browser for that site.