lundi 19 novembre 2018

OnClick Play 1 out of 5 random html5 audio tracks

I have been attempting to use the result of a random number generator to load an html5 audio file. I have the audio player and the number generator working separately, but now that it's time to wire them together, I am having trouble with it.

Here's how it works. There are 5 different tracks on my server. When the user clicks the "Remix" button, a different song should load in the html5 player's place. For example, on click, if the JS returns a 2, song2.mp3 loads. If the JS returns a 5, song5.mp3 loads and so on. I'm not even sure if this approach is possible or if it is even the best approach available to me. If anyone has any suggestions or advice, I would really appreciate it. I will paste my code below for you all to see. You will notice that I ended the script tags after the random number generator and started new tags at the beginning of the audio player code. This was just to show that the number generator works on its own.

<!DOCTYPE html>
<html>
<body>

<p>Click to remix the current track.</p>
<audio controls>
                 <source src="var x.ogg" type="audio/ogg">
                 <source src="var x.mp3" type="audio/mpeg">
                 Your browser does not support the audio element.
              </audio>
<br>
<button onclick="myFunction()">REMIX</button>

<p id="demo"></p>

<script>
//generate random number
let lastNumber // start with undefined lastNumber

function getRandNumber() {
var x = Math.floor((Math.random() * 5) + 1); // get new random number

if (x === lastNumber) { // compare with last number
return getRandNumber() // if they are the same, call the function 
again to repeat the process
}
return x // if they're not the same, return it
}
function myFunction() {
const number = getRandNumber()
lastNumber = number 
document.getElementById("demo").innerHTML = number;
}

</script>

<script>
//script to load corresponding html5 audio track
if ( var x = 1().load(song1.mp3)) {
document.getElementById("song1.mp3");

if ( var x = 2().load(song2.mp3)) {
document.getElementById("song2.mp3");

    if ( var x = 3().load(song3.mp3)) {
document.getElementById("song3.mp3");

        if ( var x = 4().load(song4.mp3)) {
document.getElementById("song4.mp3");

            if ( var x = 5().load(song5.mp3)) {
document.getElementById("song5.mp3");
}

</script>

</body>
</html>

P.S. If you have the time, please comment the code because I don't want to just solve the problem, I really want to know how and why the code works. Thanks so much!

Aucun commentaire:

Enregistrer un commentaire