在悬停状态下播放声音

时间:2012-10-15 09:30:58

标签: javascript html audio hover

我正在尝试创建一个横幅,它看起来像是一个声波,但表现得像钢琴键盘。我希望此键盘的每个键能够在悬停状态下播放短唯一声音(.ogg或.mp3样本)。

我知道如何使用Flash实现这一点,但我想坚持使用HTML / JS来完成这个项目,而我实际上已经完成了它。

“键盘”看起来像这样( SVG ):

Keyboard

你能给我一些关于如何实现这个的提示吗?

我在想<svg><canvas>或图像地图可能是不错的选择。 非常感谢你的帮助。

2 个答案:

答案 0 :(得分:5)

编辑:你可以尝试这样的事情:

演示:http://jsfiddle.net/SO_AMK/xmXFf/

jQuery的:

$("#layer1 rect").each(function(i) {
    $("#playme").clone().attr({
        "id": "playme-" + i,
        "src": B64Notes[i]
    }).appendTo($("#playme").parent());
    $(this).data("audio", i);
});
$("#layer1 rect").hover(function() {
    var playmeNum = $("#playme-" + $(this).data("audio"));
    playmeNum.attr("src", playmeNum[0].src)[0].play();
    // Reset the src to stop and restart so you can mouseover multiple times before the audio is finished
    $(this).css("fill", "red");
}, function() {
    $(this).css("fill", "#d91e63");
});​

我意识到你想避免重复,但是没有办法同时播放多个音符。

svg直接在页面中使代码更简单,因为它会从另一个域加载,阻止jQuery访问和修改它。要在从外部来源嵌入svg文档时访问该文档,请参阅:http://xn--dahlstrm-t4a.net/svg/html/get-embedded-svg-document-script.html

答案 1 :(得分:3)

如何为每个密钥分配一个ID并使用html5 <audio>? 然后使用jQuery更改音频标签的src属性?

$('#a').hover(function(){
    $('#oggfile').attr("src","a.ogg");
    $('#mpegfile').attr("src","a.mp3");
});

$('#c').hover(function(){
    $('#oggfile').attr("src","a.ogg");
    $('#mpegfile').attr("src","a.mp3");
});

$('#c').hover(function(){
    $('#oggfile').attr("src","c.ogg");
    $('#mpegfile').attr("src","c.mp3");
});
​

http://jsfiddle.net/wPGSv/

相关问题