javascript中的蓝牙耳机按钮事件检测。

时间:2018-11-25 11:55:38

标签: javascript typescript events javascript-events bluetooth

我正在构建一个可检测到耳机按钮事件的Web应用程序。插入耳机时,我成功捕获了耳机按钮事件。现在,我尝试捕获蓝牙耳机的下一个按钮事件。请对此提供任何帮助。

耳机按钮检测代码。

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

我需要类似的东西。

2 个答案:

答案 0 :(得分:2)

您可以使用keydown and keyup事件来实现长按功能。

// 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

以上方法适用于单键长按。有关密钥代码,请参见KeyCodeDemo of above

答案 1 :(得分:0)

我不相信使用内置的volumeupbutton事件将使您能够检测到单击持续了多长时间,以确定是否应将其视为增大音量或跳过曲目。相反,您应该能够将keyup / keydown事件与keyCode属性结合使用,以确定它是否是音量按钮,如下所示:

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);
  }
});

您可以使用以下代码来确定与调高音量按钮对应的keyCode:

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