yabtzey
yabtzey

Reputation: 391

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?

Upvotes: 8

Views: 15846

Answers (3)

user7892745
user7892745

Reputation:

I just wrote a quick script that simplifies the job down to only HTML for you.

(function(){
	var keyElements	= document.getElementsByTagName('keysound'),
		i			= keyElements.length,
		keys		= {};
	while (i--){
		var cur		= (keyElements[i].getAttribute('keys')||"").toString().split(''),
			v		= cur.length,
			audio	= keyElements[i].getAttribute('src'),
			caseinsensitive	= keyElements[i].getAttribute('anycase')!==null?true:false,
			regexp	= keyElements[i].getAttribute('regexp')!==null?true:false;
		if (audio){
			while (v--){
        cur[v] = caseinsensitive ? cur[v] : cur[v].toLowerCase();
        
				var src=!regexp?audio:
				audio.replace('${key}', cur[v])
				.replace('${code}', cur[v].charCodeAt(0));
				var ele = document.createElement('audio');
				ele.src = src;
				document.body.appendChild(ele);
				(keys[cur[v]] = keys[cur[v]] || []).push(
					ele
				);
				if (caseinsensitive) {
            
					(keys[cur[v].toUpperCase()] = keys[cur[v].toUpperCase()] || []).push(
						ele
					);
				}
			}
		}
	}
  console.log(keys);
	window.addEventListener('keydown',function(evt){
		var clist	= keys[evt.key] || [],
			clen	= clist.length;
		while (clen--){
			try { clist[clen].play() } catch(e) {}
		}
	});
})();
<!-- Demo code example -->
<keysound keys="0123456789abcdefghijklmnopqrstuvwxyz" regexp anycase src="https://the-peppester.github.io/styff/keys/${key}.mp3" />
<keysound keys="QWERTY" src="http://soundbible.com/mp3/Fart-Common-Everyday-Fart_Mike-Koenig.mp3" />
<keysound anycase keys="bnm,./;'[]-=+_()*&^%$#@!`~" src="http://soundbible.com/mp3/Iguana_Farts_In_A_Bathtub-Iguana_Farts-1423164123.mp3" />
<keysound anycase keys="asdfgh" src="http://soundbible.com/mp3/Uuuuuu-Paula-1357936016.mp3" />

Documentation

The script above gives special meanings to the keysound element to allow you to play sounds when a user pushes down on a key. Theese are the special attributes.

  • anycase
    • makes the keys case insenstive
  • keys=...
    • the keys that will play this sound
  • regexp
    • makes it so that the URL of each key can be different in a regexp-like manner like so:
    • ${key} in the URL will get replaced by the plain text representation of each selected key
    • ${code} in the URL will get replaced by the base 10 ASCII key code representation of each selected key
  • src=...
    • determines the URL of the audio file. Is affected by the regexp attribute

See the demo about for examples of these.

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382132

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

Upvotes: 20

Dmytro Zarezenko
Dmytro Zarezenko

Reputation: 10686

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

Upvotes: 3

Related Questions