I’m simulating a piano that plays a corresponding audio file when the appropriate key is clicked.
If I allow the length of the file to run as if the piano key was sustained, and if I long-press the click, it plays the file, and then it plays again when I release the mouse. It’s not noticeable if I simply click. If I instruct the audio to stop and reset its currentTime
attribute on release of the mouse it doesn’t do this. I wondered if there was something amiss in propagation, but I couldn’t seem to pinpoint it.
const keysObj = {
'c-key': new Audio(dir + 'key08-middleC.mp3'),
'd-key': new Audio(dir + 'key10.mp3'),
...
}
let keyPlay = (key) => {
keysObj[key.target.id].play();
}
let keyReturn = (key) => {
const isSustained = document.querySelector("input[name='sustain']:checked");
if (!isSustained) {
keysObj[key.target.id].pause();
}
keysObj[key.target.id].currentTime = 0;
}
let keyPress = (note) => {
note.onmousedown = keyPlay;
note.onmouseup = keyReturn;
}
2
Answers
So I figured it out with help from the GPT, basically I just needed to pause and reset the audio time on both mouse events to prevent the audio from replaying on mouseup when the sustain is enabled.
As a bonus, using eventListeners instead of an 'on' property makes the file play cleanly instead of having the glitchy noise initially.
But why are you playing sound files of single keys for a piano simulator when you can easily generate sounds in JavaScript? 🙂
Here’s a little sound generating utility to play with, and from which you can pinch the sound making function and do things right.
NB: If you need help with notes to frequencies for your simulator, use the arrays below…