开发者

Button Hover Sound using HTML5 Audio

Is it possible to use HTML5 to make a sound when a user hovers over one of my list item buttons? I'd like to play a very short click/chirp sound one time when a user hovers over a navigation button. I realize it won't be compatible on every browser or device and that's OK as long as it degrades gracefully. Would 开发者_如何学JAVAit be better to use Flash for this for some reason?

Edit

Also, if it's possible to do this I'd be interested in some sample code, including the javascript (if javascript is needed). I'm OK with HTML but not too handy with Javascript.


I’ve not done anything like this, but it should be possible. E.g.

<audio id="myaudio" src="myaudio.mp3"></audio>

<button onmouseover="document.getElementById('myaudio').play()">Hover me</button>

I’m not familiar with Flash, so I’m not sure if you can use JavaScript to get a Flash file to play.


This is an old answer, nowdays you can just use HTML5 really.


I'd not recommend a sound on a hover. Users can get annoyed very easily (I would).

In any case, here's how, and it doesn't need HTML5:

1) Have a simple javascript to play the sound

<script>
    function EvalSound(soundobj) {
        var thissound=document.getElementById(soundobj);
        try {
            thissound.Play(); //Quicktime, Windows Media Player, etc.
        }
        catch (e) {
            thissound.DoPlay(); //Real Player
        }
    }
</script>

2) Make an invisible embed with the sound

<embed src="mysound.wav" 
       autostart=false 
       width=0 
       height=0 
       id="mySound" 
       enablejavascript="true" />

3) Make it play on hover

<ul id="myList">
    <li onHover="EvalSound('mySound')">Foo</li>
    <li onHover="EvalSound('mySound')">Bar</li>
</ul>

Alternatively, attach event with jQuery:

<script>
    $(document).ready(function() {
        $('#myList').hover(EvalSound('mySound'));
    });
</script>

Edited because realplayer uses DoPlay() instead of Play().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜