简体   繁体   English

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

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

I am working on a project that when I used a specific keyboard's key a different sound must be played. 我正在做一个项目,当我使用特定的键盘键时,必须播放不同的声音。 I have a created a function to play the sound, then I attached an Event Listener to the DOM & finally I checked which key has been pressed & play the sound who correspond with the key. 我创建了一个播放声音的功能,然后将事件侦听器附加到DOM ,最后检查了按下了哪个键并播放与该键对应的声音。

I am trying to do this by writing DRY code. 我试图通过编写DRY代码来做到这一点。 How can I change variable sound value when calling the function to play the sound file? 调用函数播放声音文件时如何更改声音的可变值?

I have a tried changing the var sound = New Audio('filepath'); 我尝试更改var sound = New Audio('filepath'); before calling the function playSound() but it doesn't work. 在调用函数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();
  }
});

You can pass the filepath in the conditionals and assign the audio filepath in the function like this: 您可以在条件语句中传递文件路径,并在函数中分配音频文件路径,如下所示:

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