Caglar Caglar - 4 months ago 6x
HTML Question

Playing random sounds continuously on the page

<!DOCTYPE html>


<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">';

<!--play another random song-->




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,


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


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

    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.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; // Start Song