HTML5 音频播放列表在页面加载时以不同方式启动

HTML5 audio playlist start differently on page load

我有一个基本的音频播放列表,可以按特定顺序连续播放多个音轨。如何更改页面加载时的起始曲目,以便每次加载页面时播放列表都从不同的曲目开始?我刚刚找到了随机播放模式的解决方案,但这改变了播放列表的顺序,应该保持不变。只是在加载页面时寻找随机开始。感谢您的任何建议!

这是我的连续播放播放列表的工作代码。

    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>

您可以将其初始化为随机索引,而不是将 currentIndex 初始化为 -1

// 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;