我正在研究一个项目,当我使用特定键盘的键时,必须播放不同的声音。我创建了一个播放声音的函数,然后我将一个事件监听器附加到DOM,最后我检查了哪个键被按下并播放与该键对应的声音。
我试图通过编写DRY代码来做到这一点。在调用播放声音文件的功能时,如何更改可变声音值?
我有一个尝试更改var sound = New Audio('filepath');
之前调用函数playSound()
但它不起作用。
var sound = new Audio('assets/sounds/clap.wav');
// function to play sounds
function playSound() {
sound.play();
}
// adds event listener & checks keyboard to play different sounds
document.addEventListener('keydown', function(event){
if(event.keyCode == 65){
playSound();
} else if ( event.keyCode == 83 ) {
playSound();
}
else if( event.keyCode == 68 ) {
playSound();
}
else if( event.keyCode == 70 ) {
playSound();
}
});
您可以在条件中传递文件路径,并在函数中分配音频文件路径,如下所示:
var sound = new Audio('assets/sounds/clap.wav');
function playSound(filepath) {
sound.src = filepath;
sound.play();
}
// adds event listener & checks keyboard to play different sounds
document.addEventListener('keydown', function(event){
if(event.keyCode == 65){
playSound('somefilepath');
} else if ( event.keyCode == 83 ) {
playSound('somefilepath');
}
else if( event.keyCode == 68 ) {
playSound('somefilepath');
}
else if( event.keyCode == 70 ) {
playSound('somefilepath');
}
});