问题
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);
})
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?
回答1:
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;
}
来源:https://stackoverflow.com/questions/59595192/how-do-i-alter-this-function-so-that-only-one-random-song-can-be-played-at-a-ti