18910140161

JavaScript-如何在HTML中播放多首歌曲?-堆栈溢出

顺晟科技

2022-10-18 12:15:37

167

我还是个编程新手,我想做一个有我最喜欢的播放列表的网站,我想知道如何让一首歌播放,然后在第一首歌播放后,还有第二首歌?这可能吗?


顺晟科技:

下面是一个使用HTML和一些JavaScript的小示例。

// Song Index
let index = 0;
//   Elements
const music = document.querySelector('#player');
const song = document.querySelector('#song');
let current = document.querySelector('.current');
//   Array Song Path
const playlist = [
  'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3',
  'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3',
  'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3',
];
// set src
song.src = playlist[index];
player.load();
player.play();
current.innerHTML = playlist[index]

// Play Next song when song end
player.addEventListener('ended', () => {
  index += 1;
  console.log(`Next Song:${playlist[index]}`);
  // Check Playlist end
  index == playlist.length ? (index = 0) : '';
  // change src
  song.src = playlist[index];
  // Play song
  player.load();
  player.play();
  current.innerHTML = playlist[index]
});
<代码><;audio ID=“ player ”控件>;<;source ID=“ song ” SRC=“ ” type=“ audio/MP3 ”/>;<;/音频>;<;DIV类=“当前”>;歌曲路径<;/DIV>;

  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航