Connecting Tech Pros Worldwide Forums | Help | Site Map

Playing a sound file with a JavaScript function

Death Slaught's Avatar
Site Addict
 
Join Date: Aug 2007
Location: Tennessee
Posts: 952
#1   Feb 6 '08
This code was written by acoder serveral (139) days ago. So I decided to post it.

Expand|Select|Wrap|Line Numbers
  1.  
  2. function play() {
  3. embed = document.createElement("embed");
  4. embed.setAttribute("src", "soundfile.wav");
  5. embed.setAttribute("hidden", true);
  6. embed.setAttribute("autostart", true);
  7. document.body.appendChild(embed);
  8. }
  9.  
  10.  
^_^ Thanks, Death



gits's Avatar
Moderator
 
Join Date: May 2007
Location: Munich, Germany
Posts: 4,136
#2   Feb 7 '08

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 :)

Expand|Select|Wrap|Line Numbers
  1.  
  2. function play(file) {
  3.     var embed = document.createElement("embed");
  4.  
  5.     embed.setAttribute('src', file);
  6.     embed.setAttribute('hidden', true);
  7.     embed.setAttribute('autostart', true);
  8.  
  9.     document.body.appendChild(embed);
  10. }
  11.  
so now we could simply call:

Expand|Select|Wrap|Line Numbers
  1. onclick="play('file.wav');"
on any element we want ...

kind regards
acoder's Avatar
Site Moderator
 
Join Date: Nov 2006
Location: UK
Posts: 14,581
#3   Feb 7 '08

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.
gits's Avatar
Moderator
 
Join Date: May 2007
Location: Munich, Germany
Posts: 4,136
#4   Feb 7 '08

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 :)

Expand|Select|Wrap|Line Numbers
  1.  
  2. function play(file, obj) {
  3.     if (typeof obj == 'undefined') {
  4.         obj = 'object';
  5.     }
  6.  
  7.     var node = document.createElement(obj);
  8.  
  9.     node.setAttribute('src', file);
  10.     node.setAttribute('hidden', true);
  11.     node.setAttribute('autostart', true);
  12.  
  13.     document.body.appendChild(node);
  14. }
  15.  
now we could call:

Expand|Select|Wrap|Line Numbers
  1. onclick="play('file.wav');"
that creates the 'object' as default or:

Expand|Select|Wrap|Line Numbers
  1. onclick="play('file.wav', 'object');"
or even with 'embed' instead of 'object' in case we need to do that ;)

kind regards
Reply


Similar JavaScript / Ajax / DHTML bytes