You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在浏览器中检测耳机拔出?音频设备变更时暂停视频的实现问询

Hey there! Great question—browser-side detection of headphone disconnection and auto-pausing videos is totally feasible with modern Web APIs, no native code required. Let’s walk through how to implement this step by step.

1. Detecting Headphone Disconnection (Audio Device Changes)

The browser provides the devicechange event via the navigator.mediaDevices interface. This event fires whenever any media input/output device (including headphones) is added or removed. Since the event only signals a change, we’ll need to compare device lists before and after the event to identify if an audio output device was removed.

Key Notes on Permissions

To access detailed device information, you first need to get user permission to access media devices (like the microphone). Without this, browsers will return obfuscated device data that can’t be used to track changes.

Example Code for Device Change Detection

let previousOutputDevices = [];

// Fetch initial list of audio output devices (requires media permission)
async function getInitialOutputDevices() {
  try {
    // Request microphone permission to unlock device enumeration
    await navigator.mediaDevices.getUserMedia({ audio: true });
    const allDevices = await navigator.mediaDevices.enumerateDevices();
    // Filter to only audio output devices (headphones, speakers, etc.)
    return allDevices.filter(device => device.kind === 'audiooutput');
  } catch (error) {
    console.error('Failed to get device access:', error);
    return [];
  }
}

// Set up listener for device changes
async function setupDeviceChangeListener() {
  previousOutputDevices = await getInitialOutputDevices();
  
  navigator.mediaDevices.addEventListener('devicechange', async () => {
    const currentOutputDevices = await navigator.mediaDevices.enumerateDevices();
    const currentOutputIds = currentOutputDevices
      .filter(d => d.kind === 'audiooutput')
      .map(d => d.deviceId);
    const previousOutputIds = previousOutputDevices.map(d => d.deviceId);
    
    // Check if any audio output device was removed (e.g., headphones unplugged)
    const removedDevices = previousOutputIds.filter(id => !currentOutputIds.includes(id));
    if (removedDevices.length > 0) {
      console.log('Audio output device removed—likely headphones disconnected!');
      // Trigger video pause logic here
      pauseAllVideos();
    }
    
    // Update the stored device list for future comparisons
    previousOutputDevices = currentOutputDevices.filter(d => d.kind === 'audiooutput');
  });
}

// Initialize the listener
setupDeviceChangeListener();
2. Automatically Pausing Videos on Device Change

Now that we can detect the device change, let’s implement the function to pause all active videos on the page:

function pauseAllVideos() {
  // Get all <video> elements on the page
  const videos = document.querySelectorAll('video');
  
  videos.forEach(video => {
    if (!video.paused) {
      video.pause();
      console.log('Paused video:', video);
    }
  });
}
3. Alternative: Using AudioContext Interruption

As a fallback or supplementary check, you can listen for interruptions to an AudioContext. Some browsers will interrupt the audio context when headphones are unplugged, which you can capture with the statechange event:

const audioContext = new AudioContext();

audioContext.addEventListener('statechange', () => {
  if (audioContext.state === 'interrupted') {
    console.log('Audio playback interrupted—possible headphone disconnection!');
    pauseAllVideos();
  }
});

This method isn’t as reliable as devicechange (interruptions can happen for other reasons like system mute), but it can add an extra layer of detection.

Compatibility

All modern browsers (Chrome, Firefox, Edge, Safari 14.1+) support the devicechange event and enumerateDevices() API, so this solution should work for most users.

内容的提问来源于stack exchange,提问作者Souradeep Nanda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 06:28:30