简体   繁体   中英

How to get a random song to play using an array in javascript?

The page loads and the rand variable randomizes the song. I want the playagain button to pause the song and call the rand varibale again so it randomises the song again. so when i press the playbutton it will then play a different song. the playagain button is pausing the song however the rand variable is not randomizing again. is there a way to fix that?

HTML:

<audio id="mytrack" controls>
    <source src="Song1.wav" type = "audio/wav"/>
</audio>

<audio id="gd" controls>
    <source src="Song2.mp3" type = "audio/mp3"/>
</audio>

<button type="button" id="playButton"></button>
<button type="button" id="playagain"></button>

JavaScript:

var mytrackJS = document.getElementById('mytrack');
var playButtonJS = document.getElementById('playButton');
var playagainJS = document.getElementById('playagain');
var gdJS = document.getElementById('gd');

var audioPlaying = [mytrackJS, gdJS];
var rand = audioPlaying[Math.floor(Math.random() * audioPlaying.length)];

playButtonJS.addEventListener('click', playOrPause, false);
playagainJS.addEventListener('click', random, false);

function random() {

     var rand = [Math.floor(Math.random() * audioPlaying.length)];
    playOrPause();
}

function playOrPause() {
    if (!rand.paused && !rand.ended){
        rand.pause();
        playButtonJS.style.backgroundImage = 'url(playbutton.svg)';
    }
    else{
        rand.play();
        playButtonJS.style.backgroundImage = 'url(pausebutton.png)';
    }
}

It doesn't look like you're declaring the variable audioPlaying correctly. You also don't need audioPlaying[] surrounding your statement for rand. Try this instead:

var audioPlaying = [mytrackJS, gdJS];
var rand = Math.floor(Math.random() * audioPlaying.length);

Since you initialized rand variable once, its value is going to remain the same throughout.

To see expected results move it to playOrPause function.

function playOrPause() {
  var rand = audioPlaying[Math.floor(Math.random() * audioPlaying.length)];
  if (!rand.paused && !rand.ended){
    rand.pause();
    playButtonJS.style.backgroundImage = 'url(playbutton.svg)';
  } else{
    rand.play();
    playButtonJS.style.backgroundImage = 'url(pausebutton.png)';
  }
}

I'm not sure if this is what you're looking for, but instead of selecting between two different audio elements, I would just change the src attribute of a single one. This way you could have an array of file names and randomly select from those using array[Math.random()*array.length]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM