Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind a keyboard shortcut to the play and pause controls of the html audio element

This is what I thought should work but it doesn't. I'm am using unicode 112 for the "p" key and 115 for "s".

var audio = document.getElementById("lessonTrack");
window.addEventListener("keypress", playPauseKb, false);

function playPauseKb() {
  var x = event.keycode;
  if (x == 112) {
    audio.play();
  }
  else if (x == 115) {
    audio.pause();
  }
}
like image 653
Phil Avatar asked Nov 30 '25 02:11

Phil


2 Answers

You had the right idea. I added some debugging steps that you can take in the future to help you trouble shoot your code. You just have to remove the comments for testing. I also added the missing event parameter to your function. I changed the event to keyup but you can use another event if you choose, however some keyboard buttons will not respond to key down events.

You should also try and get in the habbit of using === instead of == when you can it will help prevent some possible bugs in the future. The == operator will match the value but the === operator will match the value and type. This can be a problem if you want to make sure your value is a string,number,etc.

Update: You might want use the following line of code in place of the original line to check for keypress events in firefox because it will return 0 for event.keyCode.

//check to see which event property is supported
var x = event.which || event.keyCode;  

JavaScript:

var audio = document.getElementById("lessonTrack");

window.addEventListener("keyup", playPauseKb, false);

function playPauseKb(event) {//<-- added missing event parameter


  var x = event.keyCode;

  //debug
  //console.log(x);

  //p on the keyboard
  if (x === 80) {

    audio.play();

    //alert("playing");

  } else if (x === 83) { //s button keycode

    audio.pause();

    //alert("paused");

  }
}
like image 86
Larry Lane Avatar answered Dec 02 '25 14:12

Larry Lane


Try the following: Looks like you have the wrong call to keyCode, javascript is case sensitive so keycode is not the same as keyCode

var audio = document.getElementById("lessonTrack");
window.addEventListener("keydown", function(e) {
var x = e.keyCode;
if (x === 80) { // pressed 'p'
  audio.play();
} else if (x === 83) { // pressed 's'
  audio.pause();
}
});
like image 45
aemorales1 Avatar answered Dec 02 '25 15:12

aemorales1