I'm looking to have an image, that when clicked plays a sound clip (from a list of sound clips) without repeating the same clip (until the user goes through the whole list of sounds.)
At the moment my code works but plays any one of my sound clips randomly and repeats a lot.
If anyone knows how to tweak this to make it play every clip in the list at least once before repeating that would be brilliant!
This is the code I'm using at the moment:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
function playSounds() {
var sounds = [
"AUDIO URL",
"AUDIO URL",
"AUDIO URL",
"AUDIO URL",
"AUDIO URL"
];
var index = Math.floor(Math.random() * (sounds.length));
$("#element").html("<embed src=\"" + sounds[index] + "\" hidden=\"true\" autostart=\"true\" />");
}
</script>
<a onclick="playSounds()"><img src="IMAGE URL" width="300px" id="ImageButton1"></a>
I'm guessing it's something to do with the Math.random()
part of the code?
You can use the Array as playlist and maintain the played sounds in a second array. Check my JSfiddle
<a onclick="playSounds()">
<img src="http://www.stephaniequinn.com/Ani-Piano.gif" width="300px" id="ImageButton1">
</a>
<div id="element"></div>
<script>
var sounds = ["http://www.stephaniequinn.com/Music/Allegro%20from%20Duet%20in%20C%20Major.mp3",
"http://www.stephaniequinn.com/Music/Canon.mp3",
"http://www.stephaniequinn.com/Music/Handel%20Royal%20Fireworks%20-%2007.mp3",
"http://www.stephaniequinn.com/Music/Commercial%20DEMO%20-%2009.mp3"],
oldSounds = [];
var playSounds = function () {
var index = Math.floor(Math.random() * (sounds.length)),
thisSound = sounds[index];
oldSounds.push(thisSound);
sounds.splice(index, 1);
if (sounds.length < 1) {
sounds = oldSounds.splice(0, oldSounds.length);
}
$("#element").html("<audio autoplay><source src=\"" + thisSound + "\" type=\"audio/mpeg\"><embed src=\"" + thisSound + "\" hidden=\"true\" autostart=\"true\" /></audio>");
}
</script>