I’m trying to make a (super) simple software instrument for a new project I’m working on. The way I was going about doing this is similar to Garageband’s “musical typing”, where certain notes are bound to certain keys on your keyboard. What I’ve been attempting to is bind super small mp3’s (~100kb each) to buttons and keys. The way I did this is as follows:
var a = document.createElement('audio');
var s = document.createElement('audio');
var d = document.createElement('audio');
var f = document.createElement('audio');
a.setAttribute('src', 'Sounds/a.mp3');
$('.a').click(function() {
a.currentTime = 0;
a.play();
});
$(document).jkey('a',function(){
a.currentTime = 0;
a.play();
return false;
});
For the key binding, I am using the jKey jquery plugin.
Things work (mostly) but there are a few problems:
-
In Chrome, when the key or button is pressed, the sound skips and then seems to restart again real fast. Firefox doesn’t work (firebug says it’s something to do with the
.currentTime), but Safari works perfectly. -
When holding the keydown, I would like it to NOT keep executing the function. Currently, holding the key down keeps replaying the bit, resulting in a “dun dun dun dun dun dun dun dun dun dun dun” sound.
Any suggestions on how to fix the following is much appreciated. I tried the regular ways to bind keys in Javascript and I am getting the same results, so I know it’s not jKey.
Also – if anyone has any suggestions how to go about doing this an entirely different / better way, feel free to tell me! Thanks!
I should also mention that the .current time is so that it starts replaying the note as soon as the button is pressed.
I’m not familiar with jKey, but I believe most browsers do generate multiple keydown events if a key is held down so I guess that explains the “dun dun dun dun” sound you mention. In a general sense if you want to do something exactly once when a key is pressed I think you’ll need some sort of flag that you reset on keyup. I’d suggest something like this to keep things tidy:
(You’ll need to check that for syntax errors, but I hope the general idea is obvious.)