HTML play audio using keyboard shortcut with onkeydown

Viewed 114

I can't figure out why my function isn't working to trigger the audio. Any suggestions would be very much appreciated.

tags$div(
      tags$audio(id = 'targetAudio',src = sprintf("audioResources/%s.wav", trialName), type = 'audio/wav'),
      tags$button(onclick="document.getElementById('targetAudio').play()", 
                  type = 'button', '',
                  img(src = paste0(image, 'targetIcon.png'), width = 80, height = 80)),
      tags$script("
                  var target = document.getElementById('targetAudio');
                  target.onkeydown = function(e) {
                    if (e.KeyCode === 49) {
                    target.play();
                    }
                  }
                  ")
      )

The button correctly works to trigger the audio, but I would also want to trigger the audio by using the number '1' (keycode = 49) on the keyboard.

1 Answers

From docs:

You must wrap the actual script in HTML to prevent it from being passed as text.
tags$script(HTML("if (window.innerHeight < 400) alert('Screen too small');"))

In your case;

tags$script(HTML("
  var target = document.getElementById('targetAudio');
  target.onkeydown = function(e) {
    if (e.KeyCode === 49) {
      target.play();
    }
  }
")

Also keep in mind, by using target.onkeydown you are listening keydown events on target element only. If you want to play audio with global shortcuts, you can do it like this (inside tag$script of course);

var target = document.getElementById('targetAudio');
document.addEventListener('keydown', listenKey);

function listenKey(e) {
  if(e.code === 49){
    target.play();
  }
}
Related