3

I want to add a sound clip to a button on a game I am creating. Currently It doesn't do anything and I don't know why.

At the moment In the script I have...

var audio = $(".mysoundclip")[0];
$(".minibutton").onclick(function() {
    audio.play();
});

In the HTML I have...

<audio id="mysoundclip" preload="auto">
    <source src="http://www.wav-sounds.com/cartoon/bugsbunny1.wav"></source>
</audio>

Then I have CSS for .minibutton.

Any ideas why it won't work?

4

2 回答 2

5

Your jQuery had some simple errors in it.

HTML

<audio id="mysoundclip" preload="auto">
    <source src="http://www.wav-sounds.com/cartoon/bugsbunny1.wav"></source>
</audio>
<button type="button">play</button>

jQuery

var audio = $("#mysoundclip")[0];
$("button").click(function() {
    audio.play();
});​

Fiddle: http://jsfiddle.net/iambriansreed/VavyK/

​</p>

于 2012-07-19T14:22:19.470 回答
0

Maybe I'm a too suspicous.. but

http://www.sound-effect.com/sounds1/animal/Saf/Tiger1.wav "The requested URL was not found on this server"

If that's just a typo, you should also try to figure out which audio types a browser is capable to play:

myApp.htmlAudio = (function _htmlAudioCheck() {
    var elem = document.createElement('audio'),
        bool = false;

    try {
        if( !!elem.canPlayType ) {
            bool = new Boolean(bool);
            bool.ogg = elem.canPlayType('audio/ogg; codecs="vorbis"');
            bool.mp3 = elem.canPlayType('audio/mpeg;');

            bool.wav = elem.canPlayType('audio/wav; codecs="1"');
            bool.m4a = ( elem.canPlayType('audio/x-m4a;') ||      elem.canPlayType('audio/aac;'));
        }
    } catch(e) { }

    return bool;
}());

Now we can check like

if( myApp.htmlAudio && myApp.htmlAudio.wav ) {
}

if the browser is able to playback .wav files for instance.

However, I never saw a nested source element for audio elements. That should be named track if anything. But you don't really need that here, you can just have a src attribute on the audio element itself. Example: http://jsfiddle.net/5GUPg/1/

于 2012-07-19T14:02:58.777 回答