首页 > 解决方案 > 你如何在 html 中播放多首歌曲?

问题描述

我在编码方面还是新手,我想制作一个包含我最喜欢的播放列表的网站,我想知道如何播放一首歌曲,然后在播放第一首歌曲之后,还有第二首歌曲?那可能吗?

标签: javascripthtmlcss

解决方案


这是一个包含 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" controls>
  <source id="song" src="" type="audio/mp3" />
 </audio>
<div class="current">Song Path</div>


推荐阅读