Javascript windows - 为扬声器和麦克风事件添加监听器

时间:2021-03-28 15:32:39

标签: javascript html dom-events

我想将事件侦听器绑定到 windows 对象,以检查浏览器是否正在使用扬声器和麦克风。

我的用例如下:我有一个应用程序,用户可以在其中录制音频并播放。但是,如果应用程序闲置了 60 秒,那么我希望它重新加载。

我已向 mousemovekeypress 添加了侦听器,这会阻止应用程序在被调用时重新加载,但我也想在用户录制音频或播放音频时阻止重新加载。

我能想到的方法是为这些情况(记录+回放)添加类似的事件侦听器,但我不知道如何为它们添加侦听器。

我需要类似的东西,

windows.addEventListener('speaker', () => console.log('user using speaker')

windows.addEventListener('microphone', () => console.log('user using microphone')

是否存在任何此类事件?或者有什么方法可以检查浏览器是否在使用扬声器+麦克风?

任何线索将不胜感激!

1 个答案:

答案 0 :(得分:1)

不,没有 microphonespeaker 事件。

但是!您可以使用 Event 构造函数创建自己的事件。我在这里做了一个例子,它创建了一个 microphonestartmicrophonestop 事件。每当麦克风流开始或流停止时都会发出这些事件。

async function getMicrophone() {
  // Use audio only.
  const constraints = { audio: true };

  // Create the events.
  const microphoneStartEvent = new Event('microphonestart');
  const microphoneStopEvent = new Event('microphonestop');

  // Internal function to stop the stream and fire the microphonestop event.
  const stopStream = stream => {
    const tracks = stream.getAudioTracks();
    for (const track of tracks) {
      track.stop();
    }

    window.dispatchEvent(microphoneStopEvent);
  }

  // Create the stream.
  const stream = await navigator.mediaDevices.getUserMedia(constraints);

  // You'll want to know if a stream has randomly stopped without the user's intent. 
  const tracks = stream.getAudioTracks();
  for (const track of tracks) {
    track.addEventListener('ended', () => {
      window.dispatchEvent(microphoneStopEvent);
    });
  }

  // Stream is running, fire microphonestart event.
  window.dispatchEvent(microphoneStartEvent);

  // Return both the stream and the stopStream function.
  return {
    stream,
    stopStream
  };
}

现在你可以像你的例子一样使用它,预计现在有两个事件,开始和停止。但我认为这只会让您更容易知道您的空闲逻辑何时开始和停止。

// Listen to the microphonestart event.
window.addEventListener('microphonestart', () => {
  console.log('user using microphone');
});

// Listen to the microphonestop event.
window.addEventListener('microphonestop', () => {
  console.log('user stopped using microphone');
});

// Start the stream.
getMicrophone().then(({ stream, stopStream }) => {
  // Use the stream.
  console.log(stream);

  // Stop the stream when you need.
  stopStream(stream);
}).catch(error => {
  // Catch your error.
});

至于你的演讲者;这是相同的原则。但是,它确实取决于您使用的技术。您使用 HTMLAudioElement 还是 Web Audio API?

相关问题