Search code examples
javascripthtml5-audio

Playing audio file to seek by ten seconds forward and backward while playing with keyboard


I am able to play pause and stop audio files through the keyboard, but when I am seeking back and forth, I am using left and right arrow keys, and it is being seeking 15 sec. I need to do it for 5 or 10 seconds, instead. Below is the java script that i used

       <script>
    var audio = $("audio")[0];
    $(document).keydown(function (e) {
        var unicode = e.charCode ? e.charCode : e.keyCode;
        console.log(unicode);
        // right arrow
        if (unicode == 39) {
            audio.currentTime += 5;
            // back arrow
        } else if (unicode == 37) {
            audio.currentTime -= 5;
            // spacebar
        } else if (unicode == 32) {
            if (audio.paused) {
                audio.play();
            }
            else {
                audio.pause()
            }
        }
    });
</script>

Solution

  • I am seeking back and forth, I am using left and right arrow keys, and it is being seeking 15 sec. I need to do it for 5 or 10

    You can use HTMLMediaElement.currentTime of <audio> element to set where audio should begin playing; += or -= operators to increment or decrement audio.currentTime by n seconds, for example 5 or 10seconds; check [HTMLMediaElement.paused][2] to toggle callingaudio.play()oraudio.pause()`

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
    </script>
    <audio controls autoplay src="https://upload.wikimedia.org/wikipedia/commons/6/6e/Micronesia_National_Anthem.ogg"></audio>
    <script>
      var audio = $("audio")[0];
      $(document).keydown(function(e) {
        var unicode = e.charCode ? e.charCode : e.keyCode;
        console.log(unicode);
          // right arrow
        if (unicode == 39) {
          audio.currentTime += 5;
          // back arrow
        } else if (unicode == 37) {
          audio.currentTime -= 5;
          // spacebar
        } else if (unicode == 32) {
          if (audio.paused) {
            audio.play();
          } 
          else {
            audio.pause()
          }
        }
      });
    </script>