按下键时播放声音 [英] Play a sound when a key is pressed
问题描述
是否有人知道是否有任何预定义的方式来播放从键盘输入到HTML表单的每个字母的声音?
例如:在文本字段if我输入Y,网站说Y等等。
或者,最好的方法是什么?
播放声音很容易,并且可以轻松地为按键添加处理程序,但是没有预定义的方式来链接这两个操作,因此您必须输入自己的代码
1)按键操作
document.onkeydown = function(){
...
2)播放声音
添加音频元素:
< audio id = alarm>
< source src = sound / zbluejay.wav>
< / audio>
用
执行pre >
的document.getElementById( '警报')播放();
例如,您可以建立一个将键码连接到声音元素ID的地图:
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可以找到关键代码 here
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?
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
这篇关于按下键时播放声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!