Caglar Caglar - 5 months ago 14
HTML Question

Playing random sounds continuously on the page

<!DOCTYPE html>
<html>
<body>

<audio>
</audio>

<script language="javascript">
var playlist = new Array;
playlist[0] = "sounds/0.mp3";
playlist[1] = "sounds/1.mp3";
playlist[2] = "sounds/2.mp3";
var song = document.getElementsByTagName("audio")[0];
song.innerHTML = '<source src="'+playlist[Math.floor(Math.random() * playlist.length)]+'" type="audio/mpeg">';
song.autoplay=true;

document.getElementsByTagName("audio")[0].addEventListener("ended",function(song)
{
<!--play another random song-->
});

</script>

</body>
</html>



Hello,

I wanted to make a very simple page which is going to play random songs continuously. But I couldn't figure it out. It plays just one random song and stops. By the way I am going to extend the song list. This is just a prototype.

Thanks for your help,

Answer

Here is what I changed:

  1. Refactored how you define your list
  2. Created a funtion to choose a new song (It dosnt pick the last played song)
  3. Changed getElementsByTag() to getElementById()
  4. For Debugging I added controles

Code:

<audio id="audioplayer" controls> <!-- Remove the "Controls" Attrebute if you dont want the visual controls -->
</audio>

<script>
    var lastSong = null;
    var selection = null;
    var playlist = ["sounds/0.mp3", "sounds/1.mp3", "sounds/2.mp3"]; // List of Songs
    var player = document.getElementById("audioplayer"); // Get Audio Element
    player.autoplay=true;
    player.addEventListener("ended", selectRandom); // Run function when song ends

    function selectRandom(){
        while(selection == lastSong){ // Repeat until different song is selected
            selection = Math.floor(Math.random() * playlist.length);
        }
        lastSong = selection; // Remember last song
        player.src = playlist[selection]; // Tell HTML the location of the new Song

    }

    selectRandom(); // Select initial song
    player.play(); // Start Song
</script>
Comments