1

I want to play a music playlist on my web-page in the background, I'm using chrome I don't want the console and I want autoplay but, though I write autoplay, the audio is starting only with the play button of the console. That's what I write in the HTML:

<div id="music_list">
   <audio controls autoplay></audio>
</div>

And in the Javascript

(function () {

    // Playlist array
    var files = [
        "ms4/14_1.30.mp3",
        "ms4/20_20.mp3",
        "ms4/21_34.mp3"
    ];

    // Current index of the files array
    var i = 0;

    // Get the audio element
    var music_player = document.querySelector("#music_list audio");

    // function for moving to next audio file
    function next() {
        // Check for last audio file in the playlist
        if (i === files.length - 1) {
            i = 0;
        } else {
            i++;
        }

        // Change the audio element source
        music_player.src = files[i];
    }

    // Check if the player is slected
    if (music_player === null) {
        throw "Playlist Player does not exists ...";
    } else {
        // Start the player
        music_player.src = files[i];

        // Listen for the music ended event, to play the next audio file
        music_player.addEventListener('ended', next, false)
    }

})();

How can I fix that? I'm really new in HTML and JS and I'm stuck in this problem.

  • 1
    Google's [Autoplay Policy Changes](https://developers.google.com/web/updates/2017/09/autoplay-policy-changes) of 2018. Most of all other browser implemented the same since then. – Louys Patrice Bessette Nov 14 '20 at 17:39

3 Answers3

0

I got this problem 1 year ago. The problem is of the Internet Browser you using at, for example, in Google Chrome controls autoplay doesn't work, the problem is about the permission, security and privacity of the users.

I think there is some way to make it work in any Internet Browser but, "controls autoplay" doesn't work, just in some Internet Explorers.

0

Bug players consider autoplay a bad thing because ads. At the end you will be forced to click to play. Nowadays you can try adding muted property to the audio element alongside with autoplay, and remove it after ading the first src

netizen
  • 1,028
  • 7
  • 19
  • You will try to add a muted audio as if adding an `Iframe` with a silence mp3? I tried that and it doesn't work. I think I misunderstand what are you saying because I'm new and for me Isn't easy... May you write an example, please? – stefano stoppa Nov 14 '20 at 19:58
  • Check https://stackoverflow.com/questions/50490304/how-to-make-audio-autoplay-on-chrome – netizen Nov 14 '20 at 22:22
0

This depends upon your browsers Run your code in different browsers and also try this javascript function

var mp3 = document.getElementByTagName("audio");
mp3.autoplay = true;
mp3.load();
Krutik Raut
  • 139
  • 7