[英]How do I alter this function so that only one, random song can be played at a time with each click? (JavaScript)
I'm essentially building a music generator/player app using HTML, CSS, and vanilla JavaScript where every time a user clicks a particular div with respect to a particular genre of music, a new song from that genre is played.我基本上是在使用 HTML、CSS 和 vanilla JavaScript 构建一个音乐生成器/播放器应用程序,每次用户单击特定音乐类型的特定 div 时,都会播放该类型的新歌曲。 To generate a random song, I created this JS function:
为了生成一首随机歌曲,我创建了这个 JS 函数:
const randomizeSongs = playlist => {
let song = playlist[Math.floor(Math.random() * playlist.length)];
song.play();
}
The issue I've run into is when I tried using the following code:我遇到的问题是当我尝试使用以下代码时:
const pop = document.querySelector(".pop") // Div containing audio elements
pop.addEventListener("click", (e) => {
const popSongs = document.querySelectorAll(".pop audio");
randomizeSongs(popSongs);
})
the function generated a new song with each click like I wanted to, but the previous songs generated with previous clicks didn't stop playing.该功能像我想要的那样每次点击都会生成一首新歌曲,但是以前点击生成的以前的歌曲并没有停止播放。 How can I modify the randomizeSongs function so that only one random song can play at a time with each new click?
如何修改 randomizeSongs 功能,以便每次新点击一次只能播放一首随机歌曲?
I think you're looking for pause
( https://www.w3schools.com/jsref/met_audio_play.asp ).我认为您正在寻找
pause
( https://www.w3schools.com/jsref/met_audio_play.asp )。
Haven't tried this but it would look like:没有试过这个,但它看起来像:
let previousSong;
const randomizeSongs = playlist => {
if (previousSong) {
previousSong.pause();
}
let song = playlist[Math.floor(Math.random() * playlist.length)];
song.play();
previousSong = song;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.