javascript - 你如何在 html 中播放多首歌曲?
问题描述
我在编码方面还是新手,我想制作一个包含我最喜欢的播放列表的网站,我想知道如何播放一首歌曲,然后在播放第一首歌曲之后,还有第二首歌曲?那可能吗?
解决方案
这是一个包含 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>
推荐阅读
- html - Html 元素没有通过绝对定位和内部 flexbox 占据其全部宽度
- javascript - 当用户决定更新他的个人资料信息时,我应该如何处理 JWT 令牌?
- git - 拉取请求给出了一些与权限被拒绝相关的错误
- reactjs - 如何使用打字稿客户端读取预取的服务器端数据?
- swift - 视图和视图控制器之间的委托
- python - file() 方法属于哪个 Python 模块?
- c# - 根据相机改变玩家移动的方向
- python - 用于查找/解析由空格分隔的 PDF 表的包
- java - 如何获取存储在 google-cloud-storage 存储桶的子目录中的图像的 URL
- c++ - 为什么“等待谓词”解决了条件变量的“丢失唤醒”?