Reputation: 101
Consider:
<!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>
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.
Upvotes: 0
Views: 2761
Reputation: 781
Here is what I changed:
getElementsByTag()
to getElementById()
Code:
<audio id="audioplayer" controls> <!-- Remove the "Controls" Attribute if you don't 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 the song ends
function selectRandom(){
while(selection == lastSong){ // Repeat until a different song is selected
selection = Math.floor(Math.random() * playlist.length);
}
lastSong = selection; // Remember the last song
player.src = playlist[selection]; // Tell HTML the location of the new song
}
selectRandom(); // Select initial song
player.play(); // Start song
</script>
Upvotes: 2