2

it's my first time asking question on Stack Overflow. Please excuse me for any mistakes.

I would like to know how I can change the first song played based on randomized ul. Currently, the list is being randomized each time I load the page, but the first song is always music/1.mp3. The following is my HTML and JS code:

HTML:

    <audio id="audio" preload="auto" tabindex="0" controls="" >

      <source src="music/1.mp3">

    </audio>


    <ul id="playlist">
        <li>
            <a href="music/1.mp3">
                1
            </a>
        </li>
        <li>
            <a href="music/2.mp3">
                2
            </a>
        </li>
        <li>
            <a href="music/3.mp3">
                3
            </a>
        </li>
    </ul>

JS:

    var audio;
    var playlist;
    var tracks;
    var current;
    var ul = document.querySelector('ul');
    for (var i = ul.children.length; i >= 0; i--) {
        ul.appendChild(ul.children[Math.random() * i | 0]);
    }


    init();
    function init(){
        current = 0;
        audio = $('#audio');
        playlist = $('#playlist');
        tracks = playlist.find('li a');
        len = tracks.length;
        audio[0].volume = 1;
        audio[0].play();
        playlist.find('a').click(function(e){
            e.preventDefault();
            link = $(this);
            current = link.parent().index();
            run(link, audio[0]);
        });
        audio[0].addEventListener('ended',function(e){
            current++;
            if(current == len){
                current = 0;
                link = playlist.find('a')[0];
            }else{
                link = playlist.find('a')[current];
            }
            run($(link),audio[0]);
        });
    }

    function run(link, player){
            player.src = link.attr('href');
            par = link.parent();
            par.addClass('active').siblings().removeClass('active');
            audio[0].load();
            audio[0].play();
    }
jack
  • 21
  • 2
  • http://stackoverflow.com/questions/1533910/randomize-a-sequence-of-div-elements-with-jquery#11766418 Is this what you mean? – pokeybit Jul 13 '15 at 07:27

1 Answers1

0

Add this line:

$("#audio").find("source").attr("src", $("ul li:first-child a").attr("href"));

right below the following lines:

for (var i = ul.children.length; i >= 0; i--) {
    ul.appendChild(ul.children[Math.random() * i | 0]);
}

Here is the JSFiddle demo

The problem was that your html loads the default source which is <source src="music/1.mp3"> but never changed it after the randomization until the links are clicked.

Therefore it always played the first one. Adding the code above would change the source to the first link after randomization.

Ahs N
  • 8,233
  • 1
  • 28
  • 33