Playing a sound file with a JavaScript function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Death Slaught
    Top Contributor
    • Aug 2007
    • 1137

    Playing a sound file with a JavaScript function

    This code was written by acoder serveral (139) days ago. So I decided to post it.

    [CODE=javascript]
    function play() {
    embed = document.create Element("embed" );
    embed.setAttrib ute("src", "soundfile.wav" );
    embed.setAttrib ute("hidden", true);
    embed.setAttrib ute("autostart" , true);
    document.body.a ppendChild(embe d);
    }

    [/CODE]

    ^_^ Thanks, Death
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5390

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

    [CODE=javascript]
    function play(file) {
    var embed = document.create Element("embed" );

    embed.setAttrib ute('src', file);
    embed.setAttrib ute('hidden', true);
    embed.setAttrib ute('autostart' , true);

    document.body.a ppendChild(embe d);
    }
    [/code]
    so now we could simply call:

    Code:
    onclick="play('file.wav');"
    on any element we want ...

    kind regards

    Comment

    • acoder
      Recognized Expert MVP
      • Nov 2006
      • 16032

      #3
      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.

      Comment

      • gits
        Recognized Expert Moderator Expert
        • May 2007
        • 5390

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

        [CODE=javascript]
        function play(file, obj) {
        if (typeof obj == 'undefined') {
        obj = 'object';
        }

        var node = document.create Element(obj);

        node.setAttribu te('src', file);
        node.setAttribu te('hidden', true);
        node.setAttribu te('autostart', true);

        document.body.a ppendChild(node );
        }
        [/code]
        now we could call:

        Code:
        onclick="play('file.wav');"
        that creates the 'object' as default or:

        Code:
        onclick="play('file.wav', 'object');"
        or even with 'embed' instead of 'object' in case we need to do that ;)

        kind regards

        Comment

        Working...