繁体   English   中英

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

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

我正在做一个项目,当我使用特定的键盘键时,必须播放不同的声音。 我创建了一个播放声音的功能,然后将事件侦听器附加到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');
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM