Shaharyar Kirmani
Shaharyar Kirmani

Reputation: 305

Bluetooth headphones button event detection in javascript

I am building a web app where I detect the headphones button event. I succeeded in capturing headphones button event when they are plugged in. Now I am trying to capture Bluetooth headphones next button event. Any help on this please?

Code for headphone button detection.

 document.addEventListener('volumeupbutton', () => {
   //Do something here
 }, false);

I need something similar to this.

Upvotes: 10

Views: 3022

Answers (2)

Nick Gagne
Nick Gagne

Reputation: 130

I don't believe using the built-in volumeupbutton event will allow you to detect how long the click was, to determine if it should be treated as volume-up or skip-track. Instead you should be able to use the keyup/keydown events, combined with the keyCode property to determine if it is the volume button, like this:

const longPressTime = 1500;
let volumeUpButtonTimeout;
const volumeButtonKeyCode = 0; // you'll need to determine the key code

// cross platform way to get the key code
const getKeyCode = e => {
  if (e.key !== undefined) {
    return e.key;
  } else if (e.keyIdentifier !== undefined) {
    return e.keyIdentifier;
  } else if (e.keyCode !== undefined) {
    return e.keyCode;
  }
}

document.addEventListener('keydown', e => {
  if (getKeyCode(e) == volumeButtonKeyCode) {
    volumeUpButtonTimeout = setTimeout(() => {
      // button was held for 1500ms, consider it a long-press
      // do long-press action
    }, longPressTime)
  }
});

document.addEventListener('keyup', e => {
  if (getKeyCode(e) == volumeButtonKeyCode) {
    clearTimeout(volumeUpButtonTimeout);
  }
});

You could use this code to determine what keyCode corresponds to the volume up button:

document.addEventListener('keyup', e => {
  console.log(e.keyCode);
});

Upvotes: 1

Akansh
Akansh

Reputation: 1785

You can use keydown and keyup events for implementing the long press functionality.

// Imprementation of Long Press

const longPressTime = 1500;
let keyDownTimeout;
document.addEventListener('keydown', e => {
  if (keyDownTimeout) {
    return;
  }
  keyDownTimeout = setTimeout(() => {
    // button was held for 1500ms, consider it a long-press
    if (e.code === 'ArrowUp') {
      console.log("Action Performed");
      // do long-press action
    } else {
      console.log("Other action performed");
    }
  }, longPressTime);
});

document.addEventListener('keyup', e => {
  clearTimeout(keyDownTimeout);
  keyDownTimeout = 0;
});
Press any key

The above methods work for single key long press. Refer to KeyCode for key code. Demo of above

Upvotes: 4

Related Questions