javascript 按下按键时播放声音
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12578379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Play a sound when a key is pressed
提问by yabtzey
Does anybody know if there is any predefined way to play a sound for every letter typed from keyboard into the HTML form?
有谁知道是否有任何预定义的方法可以为从键盘输入到 HTML 表单中的每个字母播放声音?
For example: In a text field if I type Y, website says Y and so on.
例如:在文本字段中,如果我键入 Y,则网站会显示 Y,依此类推。
Or, what would be the best way to do it?
或者,最好的方法是什么?
回答by Denys Séguret
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
1) 按键操作
document.onkeydown = function() {
...
2 ) play sound
2)播放声音
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 :
例如,您可以构建一个将键码链接到声音元素 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 may find keycodes here
Yoy 可以在这里找到键码
回答by Dmytro Zarezenko
You must have sound files for all letters and call them play on button press event with JavaScript.
您必须拥有所有字母的声音文件,并使用 JavaScript 在按钮按下事件上调用它们。
回答by Dmytro Zarezenko
I just wrote a quick script that simplifies the job down to only HTML for you.
我刚刚编写了一个快速脚本,将工作简化为仅适用于您的 HTML。
(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.
上面的脚本赋予了 keysound 元素特殊的含义,允许您在用户按下某个键时播放声音。这些是特殊属性。
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
anycase
- 使键大小写不敏感
keys=...
- 将播放此声音的键
regexp
- 使每个键的 URL 可以以类似正则表达式的方式不同,如下所示:
${key}
URL 中的内容将被每个选定键的纯文本表示替换${code}
URL 中的将被替换为每个选定键的基本 10 ASCII 键代码表示
src=...
- 确定音频文件的 URL。受 regexp 属性影响
See the demo about for examples of these.
有关这些示例,请参阅有关演示。