问题描述
我实质上是在使用HTML,CSS和原始JavaScript构建音乐生成器/播放器应用,其中,每次用户针对特定音乐类型单击特定div时,都会播放该类型的新歌曲.为了生成随机歌曲,我创建了以下JS函数:
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. To generate a random song, I created this JS function:
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);
})
该函数每次点击都会生成一首新歌曲,但我之前单击时生成的先前歌曲并没有停止播放.如何修改randomizeSongs函数,以便每次新点击一次只能播放一首随机歌曲?
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?
推荐答案
我认为您正在寻找pause
( https://www.w3schools.com/jsref/met_audio_play.asp ).
I think you're looking for 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;
}
这篇关于如何更改此功能,以便每次单击只能播放一首随机歌曲? (JavaScript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!