How do I alter this function so that only one, random song can be played at a time with each click? (JavaScript)

孤街醉人 提交于 2020-01-25 07:27:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!