Search code examples
htmlaudioonloadplaylist

HTML5 audio playlist start differently on page load


I have a basic audio playlist which plays continuously several audio tracks in specic order. How can I change the starting track on page load, so that everytime the page is loaded the playlist starts at different track? I just found solutions with shuffle mode, but this changes the playlist order, which should keep the same. Just looking for a random start when page is loaded. Thanks for any suggestion!

Here is my working code for the continuously playing playlist.

    const shuffledPaths = [
    'https://estherhunziker.net/_sinai/test_01.mp3',
    'https://estherhunziker.net/_sinai/test_02.mp3',
    'https://estherhunziker.net/_sinai/test_03.mp3',
    'https://estherhunziker.net/_sinai/test_04.mp3',
    'https://estherhunziker.net/_sinai/test_05.mp3'
];

// You should probably use more specific selectors, this is for the sample
const player = document.querySelector('audio');
const source = document.querySelector('source');

let currentIndex = -1;

function goNext() {
  // Grab the next path and put it in the source's src attribute
  currentIndex = (currentIndex + 1) % shuffledPaths.length;
  source.setAttribute('src', shuffledPaths[currentIndex]);

  // Load the corresponding track and play it
  player.load();
  player.play();
}

// Play the following track when the current one ended
player.addEventListener('ended', goNext);

// Play the first track
goNext();
<audio controls="controls"  >
  <source type="audio/mpeg">
</audio>


Solution

  • Instead of initializing currentIndex as -1, you could initialize it as a random index:

    // take a random index in the array, then subtract 1, because the goNext function adds 1 before playing
    let currentIndex = Math.floor(Math.random() * shuffledPaths.length) - 1;