Search code examples
javascriptfunctioneventsplayback

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.

I am trying to do this by writing DRY code. 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'); before calling the function playSound() but it doesn't work.

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

Solution

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