Search code examples
javascriptkeydownpause

Can't get audio.play() and audio.pause() to work


I am working on trying to get my audio to play and pause. I can get it to play , but have been unable to get it to pause. I'm using the keys 1, 2 ,3 ,and 4 to play different audios. Essentially, if i keydown on 1 it should play and then if i keydown on 1 again it should pause. And if I'm already playing audio from key 1 and I press key 2 it should pause audio from key 1 and play audio from key 2. I'm very new to all of this, thanks :)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Study Vibes</title>
  <link href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100;0,200;0,300;0,400;0,500;1,100;1,200;1,300;1,400;1,500&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="style.css">
</head>
<body>


  <div class="keys">
    <div data-key="49" class="key 1">
      <kbd>Vol 1</kbd>
      <span class="sound">Press 1</span>
    </div>
    <div data-key="50" class="key 2">
      <kbd>Vol 2</kbd>
      <span class="sound">Press 2</span>
    </div>
    <div data-key="51" class="key 3">
      <kbd>Vol 3</kbd>
      <span class="sound">Press 3</span>
    </div>
    <div data-key="52" class="key 4">
      <kbd>Vol 4</kbd>
      <span class="sound">Press 4</span>
    </div>
  </div>

  <audio data-key="49" class="49" src="sounds/classic_lounge.m4a"></audio>
  <audio data-key="50" class="50" src="sounds/swing_beats.m4a"></audio>
  <audio data-key="51" class="51" src="sounds/rainy_days.m4a"></audio>
  <audio data-key="52" class="52" src="sounds/summer_vibes.m4a"></audio>

<script>



function playSound(e) {  
  const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
  const key = document.querySelector(`div[data-key="${e.keyCode}"]`);
if(audio.play !== true){
audio.play();
} else if (audio.play === true){
  audio.pause();
}
}

window.addEventListener('keydown', playSound);


</script>


</body>
</html>



Solution

  • Fiddler Example (i included only one audio use number 1 only to test)

    http://jsfiddle.net/wupcdv8f/3/

    use property audio.paused to check audio state (playing/not playing).

    Here is the change i did

      if (audio.paused === true) {
        // not playing
        audio.play();
      } else if (audio.paused !== true) {
        // playing 
        audio.pause();
      }
    

    I guess the issue is .play property doesn't exist but there is a event play.using this event you can also toggle the audio state.