Playing sound files at random.

Soldato
Joined
23 Dec 2009
Posts
3,252
Location
Earth
Morning folks,

I've got this piece of code on a webpage which works fine but I'd like to extend it so that I can define a number of mp3 files, and upon pressing the enter key one of the sound files is played at random.

So the code below at the moment plays sound_file.mp3 when the enter key is pressed and stops. This is fine, I just want it to take one at random instead from a defined list of files.

Code:
$(document).keydown(function(objEvent) {
    if (objEvent.keyCode == 13) {  //tab pressed
    }
})

<audio id=playsound>
    <source src="sound_file.mp3">
</audio>

<script type="text/javascript">
document.onkeydown = function () {
    if (window.event && window.event.keyCode == 13) {
        window.event.keyCode = 13;
    }
    if (window.event && window.event.keyCode == 13)
    document.getElementById('playsound').play();
}   
</script>


Any help appreciated. Cheers.
 
Last edited:
I couldn't it it to work. :(

Here is the code that I now have. I'm no programmer so difficult for me to know where the issue is, or even if any syntax is wrong or missing.

Code:
$(document).keydown(function(objEvent) {
    if (objEvent.keyCode == 13) {  //enter pressed
    }
})

<script type="text/javascript">
var listOfFileSources = [
  "sounds/sound1.mp3",
  "sounds/sound2.mp3"
];

document.addEventListener("keydown", function () {
    if (window.event && window.event.keyCode == 13) {
      var audio = document.getElementById('listOfFileSources');
      audio.src = listOfFileSources[Math.floor(Math.random()*listOfFileSources.length)];
      audio.play();
    }
});
</script>
 
Back
Top Bottom