有没有预定义的方法可以在键盘输入HTML表单时为每个字母播放声音?
例如:在文本字段中,如果我输入 Y,则网站会说出“Y”等内容。
或者,最好的方法是什么?
有没有预定义的方法可以在键盘输入HTML表单时为每个字母播放声音?
例如:在文本字段中,如果我输入 Y,则网站会说出“Y”等内容。
或者,最好的方法是什么?
播放声音很容易,添加按键处理程序也很容易,但是没有预定义的方法将这两个操作链接起来,因此您需要自己编写代码。
1)响应按键事件
document.onkeydown = function() {
...
2) 播放声音
添加一个音频元素:
<audio id=alarm>
<source src=sound/zbluejay.wav>
</audio>
并使用以下命令执行:
document.getElementById('alarm').play();
你可以例如建立一个将按键代码与声音元素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);
}
你可以在这里找到按键码表。
您需要为所有字母准备声音文件,并使用JavaScript在按钮按下事件上播放它们。
(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" />
上述脚本赋予了 keysound 元素特殊的含义,使您可以在用户按下键时播放声音。这些是特殊属性。
anycase
keys=...
regexp
${key}
将被替换为所选键的纯文本表示形式${code}
将被替换为所选键的十进制ASCII码表示形式src=...
有关示例,请参见上面的演示。