html - How to get a random song to play using an array in javascript? -
the page loads , rand variable randomizes song. want playagain button pause song , call rand varibale again randomises song again. when press playbutton play different song. playagain button pausing song rand variable not randomizing again. there way 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)'; } }
since initialized rand variable once, value going remain same throughout.
to see expected results move 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)'; } }
Comments
Post a Comment