Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play a sound when a key is pressed

Does anybody know if there is any predefined way to play a sound for every letter typed from keyboard into the HTML form?

For example: In a text field if I type Y, website says Y and so on.

Or, what would be the best way to do it?

like image 211
yabtzey Avatar asked Sep 25 '12 07:09

yabtzey


People also ask

What happens when a key is pressed?

What happens in your computer when you press a key on your keyboard? First, a switch beneath the key closes, and current flows into a small chip in a keyboard. Each key has a scan code number, which corresponds to its position on the keyboard. The keyboard transmits this number as binary data to the computer's CPU.

How do you tell if a key is being pressed?

Visit Keyboard Checker and tap the key you want to test. If a key on the on-screen keyboard turns green, that means the keypress is being recognized however, the keyboard you see is NOT going to be an accurate representation of the keyboard you're using.


2 Answers

It's easy to play sound, and it's easy to add handlers to key press, but there is no predefined way to link the two operations so you'll have to type your own code.

1) act on key press

document.onkeydown = function() {
    ...

2 ) play sound

Add an audio element :

<audio id=alarm>
    <source src=sound/zbluejay.wav>
</audio>

And execute it with

document.getElementById('alarm').play();

You could for example build a map linking keycodes to sound element ids :

var sounds = {
   88 : 'alarm', // key 'x'
   ...

};
document.onkeydown = function(e) {
    var soundId = sounds[e.keyCode];
    if (soundId) document.getElementById(soundId).play();
    else console.log("key not mapped : code is", e.keyCode);
}

Yoy may find keycodes here

like image 157
Denys Séguret Avatar answered Oct 01 '22 21:10

Denys Séguret


You must have sound files for all letters and call them play on button press event with JavaScript.

like image 44
Dmytro Zarezenko Avatar answered Oct 01 '22 19:10

Dmytro Zarezenko