在 Vanilla JavaScript 中调用函数播放音频文件时如何更改可变音频文件值?

How to change a variable audio file value when calling a function to play the audiofile in Vanilla JavaScript?

我正在做一个项目,当我使用特定键盘的按键时,必须播放不同的声音。我创建了一个播放声音的函数,然后我将一个 Event Listener 附加到 DOM 最后我检查了哪个键被按下并播放对应的声音钥匙。

我正在尝试通过编写 DRY 代码来做到这一点。如何在调用函数播放声音文件时更改变量声音值?

我试过在调用函数 playSound() 之前更改 var sound = New Audio('filepath'); 但它不起作用。

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');
  }
});