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

React中离开页面/组件时如何关闭getUserMedia获取的媒体设备权限?

在React中离开组件时关闭媒体设备访问权限

要关闭通过getUserMedia获取的摄像头和麦克风权限,核心是停止媒体流里的所有音视频轨道。当组件卸载(离开页面/组件)时,遍历媒体流的所有轨道并调用stop()方法即可释放设备资源。

函数组件实现方案

用useEffect的清理函数处理组件卸载时的资源释放,同时用useState保存媒体流引用:

import { useState, useEffect } from 'react';

function MediaCaptureComponent() {
  const [mediaStream, setMediaStream] = useState(null);
  const videoConstraints = { width: 1280, height: 720 };

  useEffect(() => {
    // 初始化媒体设备
    const initMedia = async () => {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({
          video: videoConstraints,
          audio: true
        });
        setMediaStream(stream);
        // 将流绑定到video元素(如果需要预览)
      } catch (error) {
        console.error('获取媒体权限失败:', error);
      }
    };

    initMedia();

    // 组件卸载时清理媒体流
    return () => {
      if (mediaStream) {
        // 停止所有音视频轨道
        mediaStream.getTracks().forEach(track => track.stop());
      }
    };
  }, []);

  return (
    <div>
      {mediaStream && <video autoPlay muted srcObject={mediaStream} />}
    </div>
  );
}

export default MediaCaptureComponent;

类组件实现方案

在componentWillUnmount生命周期钩子中处理资源释放,用实例属性保存媒体流:

import React, { Component } from 'react';

class MediaCaptureComponent extends Component {
  constructor(props) {
    super(props);
    this.mediaStream = null;
    this.videoConstraints = { width: 1280, height: 720 };
  }

  async componentDidMount() {
    try {
      this.mediaStream = await navigator.mediaDevices.getUserMedia({
        video: this.videoConstraints,
        audio: true
      });
      // 将流绑定到video元素
      this.videoElement.srcObject = this.mediaStream;
    } catch (error) {
      console.error('获取媒体权限失败:', error);
    }
  }

  componentWillUnmount() {
    if (this.mediaStream) {
      // 停止所有轨道释放设备
      this.mediaStream.getTracks().forEach(track => track.stop());
    }
  }

  render() {
    return (
      <div>
        <video ref={el => this.videoElement = el} autoPlay muted />
      </div>
    );
  }
}

export default MediaCaptureComponent;

关键说明

  • 必须保留媒体流的引用(不管是用useState还是实例属性),否则卸载时无法找到对应的轨道进行停止操作。
  • 调用track.stop()后,浏览器会自动终止对摄像头和麦克风的访问,界面上的设备占用标记也会消失。

内容的提问来源于stack exchange,提问作者Brij Vaghani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 21:01:09