浏览器自带api

    // 检测设备是否存在(不请求权限,结果可能受隐私限制影响)
    async checkDevices() {
      if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {
        console.log('浏览器不支持免授权媒体设备检测');
        this.checkDevicesWithPermission()
        return
      }

      try {
        const devices = await navigator.mediaDevices.enumerateDevices();
        this.hasMicrophone = devices.some(device => device.kind === 'audioinput');
        this.hasCamera = devices.some(device => device.kind === 'videoinput');
        if (!this.hasMicrophone || !this.hasCamera) await this.checkDevicesWithPermission()
      } catch (error) {
        console.error('设备免授权检测失败:', error);
        this.checkDevicesWithPermission()
      }
    },
    // 精确检测(请求用户授权,结果更可靠)
    async checkDevicesWithPermission() {
      if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        console.log('浏览器不支持媒体访问');
        this.hasMicrophone = false;
        this.hasCamera = false;
        return
      }

      try {
        // 请求媒体访问权限
        const stream = await navigator.mediaDevices.getUserMedia({
          audio: true,
          video: true
        });

        // 停止媒体流(避免持续占用设备)
        stream.getTracks().forEach(track => track.stop());
        // 枚举已授权设备
        const devices = await navigator.mediaDevices.enumerateDevices();
        console.log(devices);
        this.hasMicrophone = devices.some(d => d.kind === 'audioinput');
        this.hasCamera = devices.some(d => d.kind === 'videoinput');
        console.log('设备检测结果', this.hasMicrophone, this.hasCamera)
      } catch (error) {
        // 处理拒绝授权或硬件错误
        const isPermissionDenied = error.name === 'NotAllowedError';
        const isNoDevice = error.name === 'NotFoundError';

        console.error(
          isPermissionDenied ? '用户拒绝授权'
            : isNoDevice ? '未找到设备' : '检测失败', error
        );
        this.hasMicrophone = false;
        this.hasCamera = false;
      }
    },

正常物理设备以上代码检测没有问题,但是桌面云类的虚拟声卡检测时,navigator.mediaDevices.enumerateDevices()报错提示NotFoundError,但实际控制台执行是能正常打印出设备的。

声网api

    async rctCheckDevices() {
      try {
        const devices = await AgoraRTC.getDevices()
        this.hasMicrophone = devices.some(d => d.kind === 'audioinput');
        this.hasCamera = devices.some(d => d.kind === 'videoinput');
        console.log('------设备检测-------', devices, this.hasMicrophone, this.hasCamera);
      } catch (error) {
        this.hasMicrophone = false;
        this.hasCamera = false;
        console.error('检测失败', error);
      }
    },
Last Updated:
Contributors: haizhiguang