morgi
morgi

Reputation: 1025

Play a sound on hover state

I'm trying to create a banner that would somehow look like a soundwave but behave like a piano keyboard. I'd like each key of this keyboard to play a short unique sound (.ogg or .mp3 samples) on hover state.

I know how to implement this using Flash but I'd like to stick to HTML/JS for this project and I'm having trouble actually getting it done.

The "keyboard" would look like this (SVG) :

Keyboard

Could you give me a few hints on how to implement this?

I'm thinking <svg>, <canvas>, or image maps could be good options. Thank you very much for your help.

Upvotes: 4

Views: 2841

Answers (2)

A.M.K
A.M.K

Reputation: 16785

EDIT: You can try something like this instead:

Demo: 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");
});​

I realize that you want to avoid duplication but there's no way to have multiple notes playing at the same time otherwise.

The svg is directly in the page to make the code simpler and because it would load from another domain preventing the jQuery from accessing and modifying it. To access the svg document when it's embedded from an external source, please see: http://xn--dahlstrm-t4a.net/svg/html/get-embedded-svg-document-script.html

Upvotes: 5

user1537415
user1537415

Reputation:

How about assigning each key an id and using html5 <audio>? Then using jQuery change the src attribute of audio tag?

$('#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/

Upvotes: 3

Related Questions