javascript - 如何在使用 JS 结束第一首曲目后自动播放另一首曲目?
问题描述
我试图弄清楚如何在第一首曲目自动结束后立即播放另一首曲目,然后整个曲目再次循环,直到用户按下暂停。
var myAudio = document.getElementById("myAudio");
var isPlaying = false;
function togglePlay() {
isPlaying ? myAudio.pause() : myAudio.play();
};
myAudio.onplaying = function() {
isPlaying = true;
};
myAudio.onpause = function() {
isPlaying = false;
};
<audio id="myAudio" src="/sound/track.mp3" preload="auto" loop="true">
</audio>
<button id="play-pause"><a onClick="togglePlay()">PLAY/PAUSE SOUND</a></button>
解决方案
Firstable 不写内联 JavaScript,它有很多缺点,而且由于您想在当前结束时更改歌曲,所以您应该摆脱该loop
属性,因为您不想只播放一首歌曲,并且您不需要跟踪音频元素的播放状态,它已经有一个属性audio.paused
来判断它是否正在播放,我认为没有理由<a>
在按钮元素内添加标签,这是播放一些歌曲的示例播放列表都是动态的,随意添加您想要的歌曲数量
var myAudio = document.getElementById("myAudio"),
// a simple playing list
playingList = ["v1601656608/lambada_saxo_bxdmys", "v1601656600/coffin_dance_saxo_ze81hy", "v1601656611/mr_saxobeat_saxo_snh2di"],
currentSong = 0;
// set the initial song url to be the first song in the playlist
myAudio.src = `https://res.cloudinary.com/dzcscgx8y/video/upload/${playingList[0]}.mp3`;
document.querySelector("#play-pause").onclick = function() {
myAudio.paused ? myAudio.play() : myAudio.pause();
}
myAudio.onended = function() {
// change the src to be the url of the next song, if the song is the last one in the playlist then the next should be the first one
this.src = `https://res.cloudinary.com/dzcscgx8y/video/upload/${playingList[++currentSong === playingList.length ? 0 : currentSong]}.mp3`;
// the audio player stops after playing each song, so after changing the src just launch the player
this.play();
}
<audio id="myAudio" src="" preload="auto"></audio>
<button id="play-pause">PLAY/PAUSE SOUND</button>
推荐阅读
- c - How to create a pointer to pointer on the Heap
- firebase - 如何在另一个小部件中获取 Firestore 数据
- dhall - 为什么 Dhall 不允许从 if 表达式返回类型?
- reactjs - 使用 Axios 从 Reactjs 中的 Api 获取数据
- angular - 来自功能模块的角度注册依赖项
- java - 我不知道为什么 NumberFormatException 会在这里发生。我想对文章总数进行分页并打印出来
- r - 在R中为多个图形添加标题
- c# - 是否可以检测 BinaryReader.ReadBytes(int) 是否到达流的末尾?
- javascript - React Native:如何从自定义抽屉中调度 redux 操作
- c# - 从数据(函数)vue中的ViewBag获取项目