...

View Full Version : Play sound file randomly



jameswsparker
11-15-2010, 11:44 PM
Hello geniuses. :thumbsup: :)

I really need your help and didn't know who else to turn to.

Using JavaScript, I require a code that allows me to play .wav sound files randomly and automatically on page start-up, I also need them to loop as they are drum beats.

The plan: to load my web page and hear a random drum beat that loops continuously.

I need it to be compatible with most, if not all Internet browsers (Chrome, Internet Explorer, Firefox and Opera are crucial) and to state what sound file is playing on the page (allowing me to identify the looping drum beat/sound file), and if possible to provide a link to the actual sound file for download.

I've tried endlessly trying to find code to build upon but have failed miserably, I would appreciate any code submissions as it would help me out massively.
It's a lot to ask I know, but it would be so very appreciated. :confused:
My knowledge with JavaScript is sadly minimal.

I've also got a quick question, how would I prevent Google Chrome from putting a pause after each sound loop? Of course, being drum beats; I require it to loop in sync and it appears only Google Chrome puts a 1 second period after each play. :(

Please help, I am so stuck.
Anyway guys, thanks for reading! :o

Old Pedant
11-16-2010, 12:00 AM
*NOT TESTED*



<html>
<head>
<script type="text/javascript">
function startSound( )
{
var sounds = [
"jungle_rhythms", "heartbeat", "pulse",
... any number of file names ...
... do not put comma after the LAST one ...
];

var sound = Math.floor( Math.random() * sounds.length );
var where = document.getElementById("soundHolder");
var name = document.getElementById("soundName");
where.innerHTML =
'<embed src="/path/to/sounds/' + sound + '.wav" autostart="true" width="0" height="0" '
+ ' repeat="true" loop="true" enablejavascript="false" />';
name.innerHTML = sound;
}
</script>
</head>
<body onload="startSound( )">
...
... someplace in body ...

<span id="soundHolder" style="visibility: hidden;"></span>
...
Now playing: <span id="soundName"></span>
...
</body>
</html>

I think IE uses repeat and other use loop, but not sure. In any case shouldn't hurt to use both.

Old Pedant
11-16-2010, 12:02 AM
Can't help you w/ Chrome and the 1 second pause. Never noticed it before, but never looked for it, either.

jameswsparker
11-16-2010, 12:31 AM
Thank you for your swift response, I was quite amazed at how fast you compiled that code.

But I have encountered a few problems that I really need help with:

. I can only ever get it to play the first wave file in the code and have tried swapping the files around to confirm they weren't bust.
. It often states 'Now playing: 0', is there a way I can get it to state the actual sequence number and title of the file?
. The code appears to be incompatible with Internet Explorer and only works in Google Chrome. :(
. I don't know how to make it display a hyper to the sound file it's playing.

Can you help me? :(
You've been brilliant so far. :)

Old Pedant
11-16-2010, 12:47 AM
Hmmm...I really thought that would work with MSIE.

And it *certainly* should be picking a random file.

Can you copy/paste the code you are actually using? Might be a typo in it.

As for the URL: Easy.

Change the span to a link:

Now playing: <a id="soundName" href="#"></a>

and change

name.innerHTML = sound;
to


name.href = "/path/to/sounds/" + sound + ".wav"
name.innerHTML = sound;

Old Pedant
11-16-2010, 12:52 AM
Yeah, here's a demo I did a while back.
http://www.mywhizbang.com/imagemapdemo.html

Click on one of the two balloons. In MSIE.

So I dunno what is different about this code.

MattF
11-16-2010, 12:54 AM
Using JavaScript, I require a code that allows me to play .wav sound files randomly and automatically on page start-up, I also need them to loop as they are drum beats.

The plan: to load my web page and hear a random drum beat that loops continuously.

Some users/visitors are going to hate you with a vengeance if you automatically start any noise playing on page load. Don't do it. If someone wants to listen to anything on your site, allow them to make that choice. Don't force it upon them.

Old Pedant
11-16-2010, 12:55 AM
Oh, sheesh! What a DOOFUS!

SORRY!

This line:

var sound = Math.floor( Math.random() * sounds.length );
should be


var sound = sounds[ Math.floor( Math.random() * sounds.length ) ];

DOH DOH DOH

Heck, I don't know how you got any sound AT ALL!

jameswsparker
11-16-2010, 01:09 AM
@MattF This is a page for personal use, and not public.

I am working on a personal project.

jameswsparker
11-16-2010, 01:11 AM
Old Pedant

Thank you for all your help also, I literally copied the entire code you gave me and saved it as an individual HTML file. I have made NO alternations apart from the file names, and removing the comma as requested.

Old Pedant
11-16-2010, 01:12 AM
Catch up with my posts. I've given you one addendum and one correction now. Have you implemented them?

But when in doubt, always re-post code. Sometimes a typo slips in from the original poster (and sometime a huge goof slips in...doh).

jameswsparker
11-16-2010, 01:18 AM
Hello, I am suffering the following problems:
. No sound at all in any browser.
. And once the link is clicked, it says it cannot find FILENAME.wav.wav, it has two .wav file extension tags.

Haa ha, I'm amazed we got this far! :D

My entire code is exactly as follows:

<html>
<head>
<script type="text/javascript">
function startSound( )
{
var sounds = [
"badrat1.wav", "badrat2.wav", "test.wav"
];

var sound = sounds[ Math.floor( Math.random() * sounds.length ) ];
var where = document.getElementById("soundHolder");
var name = document.getElementById("soundName");
where.innerHTML =
'<embed src="/loops/' + sound + '.wav" autostart="true" width="0" height="0" '
+ ' repeat="true" loop="true" enablejavascript="false" />';
name.href = "/loops/" + sound + ".wav"
name.innerHTML = sound;
}
</script>
</head>
<body onload="startSound( )">

<span id="soundHolder" style="visibility: hidden;"></span>

Now playing: <a id="soundName" href="#"></a>
</body>
</html>

Old Pedant
11-16-2010, 01:26 AM
Next time, use [ code ] and [ /code ] around your coding. Or highlight the code in the text window and then click on the # symbol in the icons above the window.

Old Pedant
11-16-2010, 01:28 AM
Yes, you will note that I *CAREFULLY* omitted the ".wav" from the name of my sound files. I did that on purpose. So I wouldn't have to strip off the ".wav" when displaying the name of the file in the browser.

I'm looking to see if there's more.

Old Pedant
11-16-2010, 01:31 AM
I don't see anything else.

If you want to display "badrat1.wav" instead of just "badrat1" then you can leave the ".wav" on the ends of the file names and just remove that from the coding:


where.innerHTML =
'<embed src="/loops/' + sound + '" autostart="true" width="0" height="0" '
+ ' repeat="true" loop="true" enablejavascript="false" />';
name.href = "/loops/" + sound;

Sciliano
11-16-2010, 01:42 PM
jameswsparker:

Specify the full path to the media files, when testing:


<!DOCTYPE HTML>
<html>
<head>
<title>None</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">

// local folder was used for testing
// change to the media files path on your site;

var mediaFile = ["song1.mp3","song2.mp3","song3.mp3",
"song4.mp3","song5.mp3"];
var mediaPath = "c:/Documents and Settings/ABC.SELF-C18DAAD6BD/Desktop/My Site/media/";
var rotateDelay = 10; // 3 seconds;


/* ********* Do not edit below this line ************* */

var randomOrder = [];
var rotateTimer = "";
var mediaFileName = "";
var playerEmbedStr = '\<embed type="application\/x-mplayer2" width="325" height="52" showstatusbar="1" enablecontextmenu="false" src="mediaFileName"\>\<\/embed>';

function swapMedia(nSong){

document.getElementById('playerContainer').innerHTML = playerEmbedStr;
var activePlayerStr = playerEmbedStr.replace("mediaFileName", mediaPath + nSong);
document.getElementById('playerContainer').innerHTML = activePlayerStr;

}

function rotate(){

swapMedia(mediaFile[randomOrder[0]]);
if (randomOrder.length > 0)
{
randomOrder.shift();
if (randomOrder.length != 0)
{
rotateTimer = setTimeout("rotate()", rotateDelay * 1000);
}
else {
var nBtn = document.forms[0]['startBtn'];
nBtn.disabled = true;
setTimeout(function()
{
nBtn.disabled = false;
nBtn.value = "Start New Bingo";
document.getElementById('playerContainer').innerHTML = '\<embed type="application\/x-mplayer2" width="325" height="52" showstatusbar="1" enablecontextmenu="false" \>\<\/embed>';
} , rotateDelay * 1000)
shuffle();
}
}
}

function shuffle(){

for (i=0; i<=mediaFile.length-1; i++)
{
randomOrder[i] = i;
}
for (i=0; i<randomOrder.length; i++)
{
var tmp1 = parseInt(Math.random()*randomOrder.length);
var tmp2 = parseInt(Math.random()*randomOrder.length);
var tmp3 = randomOrder[tmp1];
randomOrder[tmp1] = randomOrder[tmp2];
randomOrder[tmp2] = tmp3;
}
}

function init(){

shuffle();
document.forms[0]['startBtn'].onclick = function()
{
var currState = document.forms[0]['startBtn'];
var nActive = currState.value == "Start Bingo" || currState.value == "Start New Bingo" ? true : false;
if (nActive)
{
rotate();
currState.value = "Stop Bingo";
}
else {
clearTimeout(rotateTimer);
document.getElementById('playerContainer').innerHTML = '\<embed type="application\/x-mplayer2" width="325" height="52" showstatusbar="1" enablecontextmenu="false" \>\<\/embed>';
currState.value = "Start New Bingo";
shuffle();
}
}
}

navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);

</script>
<style type="text/css">

body {background-color: #fffacd; margin-top: 60px;}

</style>
</head>
<body>
<div id="playerContainer">
<embed type="application/x-mplayer2" width="325" height="52" showstatusbar="1" enablecontextmenu="false"></embed>
</div>

<form action="">
<input type="button" name="startBtn" value="Start Bingo">
</form>

</body>
</html>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum