I am building a web-app which includes a form and (as a progressive enhancement / UX effect) I would like a keypress to fire a keystroke sound effect.
I have cut the .mp3 sound effect quite short (0.18s).
Nevertheless, there appears to be an audible delay when I test my setup on Firefox on my laptop (and not every keypress fires the sound effect).
On Firefox Mobile on my Android, very few keypresses fire the sound effect - maybe one keypress in every eight.
Am I trying to achieve something which can't be done using present web technology, or am I simply approaching this the wrong way?
Here is my setup:
var myInput = document.getElementsByTagName('input')[0];
var keypress = document.getElementsByClassName('keypress')[0];
function playSoundEffect() {
keypress.play();
}
myInput.addEventListener('keydown', playSoundEffect, false);
/* I've also tried...
myInput.addEventListener('keyup', playSoundEffect, false);
myInput.addEventListener('keypress', playSoundEffect, false);
*/
input {
width: 90vw;
}
<input type="text" placeholder="Type to hear the sound effect..." />
<audio class="keypress">
<source src="http://handsoffhri.org/.assets/theme/elements/mp3/keypress.mp3" type="audio/mpeg">
</audio>
Second Attempt:
Thanks to the helpful comments below from @StackingForHeap and @zero298, I have refactored my setup:
var myInput = document.getElementsByTagName('input')[0];
function playSoundEffect() {
var jsKeypress = new Audio('http://handsoffhri.org/.assets/theme/elements/mp3/keypress.mp3');
jsKeypress.play();
}
myInput.addEventListener('input', playSoundEffect, false);
input {
width: 90vw;
}
<input type="text" placeholder="Type to hear the sound effect..." />
This is definitely an improvement - creating a new Audio
object each time allows for each one to start playing independently of any previously created Audio
objects.