在 JavaScript 中释放按键时如何停止声音 [英] how do i stop a sound when a key is released in JavaScript
问题描述
我正在为我和我的朋友编写一个全气喇叭钢琴(我知道这有点愚蠢),我必须完成所有的键绑定,然后我遇到了这个问题,当我松开按键时声音不会停止被按下以激活它.
i am coding a full air horn piano for me and my friends (kind of dumb i know) and i got to doing all the key binds and then i ran into this problem, the sounds wont stop when i release the key that was pressed to activate it.
这是我目前在 .js 文件中的内容(到目前为止只输入了一个声音):
here is what i have so far in the .js file(just one sound put in so far):
function startAnatural(){
var A = new Audio("A natural.mp3");
A.play();
}
function stopAnatural(){
var A = new Audio("A natural.mp3");
A.pause();
A.currentTime = 0;;
}
document.onkeydown = function(e){
e = e || window.event;
var key = e.which || e.keyCode;
if(key===81){
startAnatural();
}
};
document.onkeyup = function(e){
e = e || window.event;
var key = e.which || e.keyCode;
if(key===81){
stopAnatural();
}
};
推荐答案
您正在创建相同声音的新实例并暂停它,而原始实例继续播放.
You're creating a new instance of the same sound and pausing it, whilst the original instance carries on playing.
相反,两个函数都需要引用同一个 Audio
对象.
Instead, both functions need to have a reference to the same Audio
object.
也许这样的设计更适合你.
Maybe a design like this would work better for you.
function createSound(file) {
var sound = new Audio(file);
return {
start: function() {
sound.play();
},
stop: function() {
sound.pause();
sound.currentTime = 0;
}
};
}
此函数采用您要加载的声音的名称,然后返回用于启动和停止它的另外两个函数.这两个函数将始终引用同一个 Audio
实例.
This function takes the name of a sound you want to load, then returns two other functions for starting and stopping it. Both functions will always refer to the same Audio
instance.
var aNatural = createSound('A natural.mp3');
document.onkeydown = function() {
// ...
aNatural.start();
// ...
}
document.onkeyup = function() {
// ...
aNatural.stop();
// ...
}
<小时>
如果您想组织所有声音,您需要根据相应的键码存储声音.
If you want to organize all of your sounds, you'll want to store the sounds against the corresponding keycodes.
var notes = [
{ key: 81, sound: createSound('A natural.mp3') },
{ key: 82, sound: createSound('B natural.mp3') },
{ key: 83, sound: createSound('C natural.mp3') }
// ...
];
然后您可以创建事件侦听器,使用适当的键代码触发每个声音.
Then you can create event listeners trigger each sound with the appropriate key code.
document.onkeydown = function() {
var pressedKey = e.which;
notes.forEach(function(note) {
if(note.key === pressedKey) {
note.sound.start();
}
});
}
// do the same for keyup
// ...
这篇关于在 JavaScript 中释放按键时如何停止声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!