Playing a sound file with a JavaScript function 
February 6th, 2008, 02:49 PM
|  | Site Addict | | Join Date: Aug 2007 Location: Tennessee
Posts: 952
| |
This code was written by acoder serveral (139) days ago. So I decided to post it. -
-
function play() {
-
embed = document.createElement("embed");
-
embed.setAttribute("src", "soundfile.wav");
-
embed.setAttribute("hidden", true);
-
embed.setAttribute("autostart", true);
-
document.body.appendChild(embed);
-
}
-
-
^_^ Thanks, Death
| 
February 7th, 2008, 10:05 AM
|  | Moderator | | Join Date: May 2007 Location: Munich, Germany
Posts: 4,102
| | | re: Playing a sound file with a JavaScript function
to make it a little bit more useful we should slightly adapt it to accept the file to play as a parameter, and strictly seen we should declare the variable embed :) -
-
function play(file) {
-
var embed = document.createElement("embed");
-
-
embed.setAttribute('src', file);
-
embed.setAttribute('hidden', true);
-
embed.setAttribute('autostart', true);
-
-
document.body.appendChild(embed);
-
}
-
so now we could simply call: - onclick="play('file.wav');"
on any element we want ...
kind regards
| 
February 7th, 2008, 10:10 AM
|  | Site Moderator | | Join Date: Nov 2006 Location: UK
Posts: 14,520
| | | re: Playing a sound file with a JavaScript function
I probably posted that from somewhere - no need to attribute it to me.
Besides the points made above, embed is actually non-standard, but sometimes required for backwards compatibility. The element to use now is object.
| 
February 7th, 2008, 11:21 PM
|  | Moderator | | Join Date: May 2007 Location: Munich, Germany
Posts: 4,102
| | | re: Playing a sound file with a JavaScript function Quote: |
Originally Posted by acoder I probably posted that from somewhere - no need to attribute it to me.
Besides the points made above, embed is actually non-standard, but sometimes required for backwards compatibility. The element to use now is object. | so we could adapt it further :) -
-
function play(file, obj) {
-
if (typeof obj == 'undefined') {
-
obj = 'object';
-
}
-
-
var node = document.createElement(obj);
-
-
node.setAttribute('src', file);
-
node.setAttribute('hidden', true);
-
node.setAttribute('autostart', true);
-
-
document.body.appendChild(node);
-
}
-
now we could call: - onclick="play('file.wav');"
that creates the 'object' as default or: - onclick="play('file.wav', 'object');"
or even with 'embed' instead of 'object' in case we need to do that ;)
kind regards
|  |
Similar Threads | | Thread | Thread Starter | Forum | Replies | Last Post | | Play a sound | Rick Lederman | answers | 3 | November 19th, 2005 01:11 AM | | Sound Files in webpages? | John | answers | 7 | July 17th, 2005 03:37 AM | | | | /bytes/about
We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights.
Get the best answers to your questions from over 225,662 network members.
|