Angular6 未能在“MediaDevices”上执行“getUserMedia”:必须至少请求一个音频和视频

Angular6 未能在“MediaDevices”上执行“getUserMedia”:必须至少请求一个音频和视频,angular6,typescript2.0,getusermedia,audiocontext,Angular6,Typescript2.0,Getusermedia,Audiocontext,我用的是AudioContext,程序化的,和Typescript 这是我的密码: /** * Checks for getUserMedia * * @params: none * @returns: any */ public hasGetUserMedia(): any { const mediaservices = !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia); con

我用的是AudioContext,程序化的,和Typescript

这是我的密码:

/**
 * Checks for getUserMedia
 *
 * @params: none
 * @returns: any
 */
public hasGetUserMedia(): any {
  const mediaservices = !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);
  console.log('Media Services: ', navigator.mediaDevices);
  return mediaservices;
}

/**
 * A function to get the return value of hasGetUserMedia
 *
 * @params: none
 * @return: none
 */
public isUserMediaGood(micstatus: boolean) {
  const self = this;
  if (this.hasGetUserMedia()) {
    // Good to go!
    self.isUserMediaThere = true;
    console.log('We have User Media Houston!');

    // Now accessInputDevice
    this.accessInputDevice(micstatus);
  } else {
    // Oops!
    self.isUserMediaThere = false;
    console.log('WARNING: getUserMedia() is not supported by your browser');

  }
}

public accessInputDevice(micstatus: boolean) {
  window.AudioContext = window.AudioContext;

  const context = new AudioContext();
  const constraints = {
    audio: micstatus,
    video: false
  }

  // initialization
  if (localStorage.getItem('microphone') === null) {
    // just assume it is prompt
    localStorage.setItem('microphone', 'prompt');
  }

  // Then somewhere
  navigator.getUserMedia({audio: true}, function (e) {
    // http://stackoverflow.com/q/15993581/1008999
    //
    // In chrome, If your app is running from SSL (https://),
    // this permission will be persistent.
    // That is, users won't have to grant/deny access every time.
    localStorage.setItem("voice_access", "granted");

  }, function (err) {
    if (err.name === 'PermissionDismissedError') {
      localStorage.setItem('voice_access', 'prompt')
    }
    if (err.name === 'PermissionDeniedError') {
      localStorage.setItem('voice_access', 'denied');
    }
  })

  navigator.mediaDevices.getUserMedia(constraints)
    .then((stream) => {
      const microphone = context.createMediaStreamSource(stream);
      const filter = context.createBiquadFilter();

      // microphone -> filter -> destination
      console.log('Mic: ', microphone);

      microphone.connect(filter);
      filter.connect(context.destination);
    });
}

public gotDevices(deviceInfos: any) {

  for (let i = 0; i !== deviceInfos.length; ++i) {
    const deviceInfo = deviceInfos[i];
    const option = document.createElement('option');
    option.value = deviceInfo.deviceId;
    if (deviceInfo.kind === 'audioinput') {
      option.text = deviceInfo.label || 'microphone ';
      // this.microphone.appendChild(option);

      console.log('Found device: ', deviceInfo);

      //    } else if (deviceInfo.kind === 'videoinput') {
      //      option.text = deviceInfo.label || 'camera ' +
      //        (videoSelect.length + 1);
      //      videoSelect.appendChild(option);
    } else {
      console.log('Found another kind of device: ', deviceInfo);
    }
  }
}

public getStream() {
  const self = this;
  const constraints = {
    audio: {
      audio: false,
      deviceId: {exact: self.microphone.id}
    },
    //      video: {
    //        deviceId: {exact: videoSelect.value}
    //      }
  };

  navigator.mediaDevices.getUserMedia(constraints).
    then(self.gotStream).catch(self.handleError);
}

public gotStream(stream: any) {
  const self = this;
  window.AudioContext = stream; // make stream available to console
  self.microphone = stream;

}

public handleError(error: any) {


  // log to console first
  console.error('Error: ', error); /* handle the error */
  if (error.name === 'NotFoundError' || error.name === 'DevicesNotFoundError') {
    // required track is missing
  } else if (error.name === 'NotReadableError' || error.name === 'TrackStartError') {
    // webcam or mic are already in use
  } else if (error.name === 'OverconstrainedError' || error.name === 'ConstraintNotSatisfiedError') {
    // constraints can not be satisfied by avb. devices
  } else if (error.name === 'NotAllowedError' || error.name === 'PermissionDeniedError') {
    // permission denied in browser
  } else if (error.name === 'TypeError' || error.name === 'TypeError') {
    // empty constraints object
  } else {
    // other errors
  }

}
我的问题是我得到了错误:未捕获承诺:TypeError:未能在“MediaDevices”上执行“getUserMedia”:必须至少请求一个音频和视频

TypeError:未能在“MediaDevices”上执行“getUserMedia”:必须至少请求一个音频和视频

错误发生在以下位置:

我想知道为什么会这样

更新:

因此,我从这里实施了这个解决方案:

然后,我点击这个链接:

然后发现当AUDIO:false和VIDEO:false同时出现时抛出类型ERROR:

我需要保留视频:假。为什么?我对打开视频不感兴趣,用户认为我们的软件是间谍软件而感到害怕。这是一个隐私问题。

这是我实现的代码:

注意:当用户单击麦克风图标时,会传递micstatus。当用户单击时,它将关闭或为FALSE。当用户再次单击时,它将传递或为TRUE。但是,如果视频保持为FALSE,则会触发类型错误。那是我的问题。CHROME不允许将FALSE、FALSE传递到getUserMedia方法中。最后一个错误被触发。这就是我需要解决的问题:关闭视频,打开或关闭音频,这样就不会抛出类型错误


您需要使用异步方法navigator.permissions检查camera和micro的权限。查询{name:'camera'/*和'Mirror'*/}

这个函数返回包含站点权限信息的对象

例如:

const checkForVideoAudioAccess = async () => {
        try {
          const cameraResult = await navigator.permissions.query({ name: 'camera' });
          // The state property may be 'denied', 'prompt' and 'granted'
          this.isCameraAccessGranted = cameraResult.state !== 'denied';

          const microphoneResult = await navigator.permissions.query({ name: 'microphone' });
          this.isMicrophoneAccessGranted = microphoneResult.state !== 'denied';
        } catch(e) {
          console.error('An error occurred while checking the site permissions', e);
        }

        return true;
      }
阅读有关权限的详细信息:

之后,您可以在使用getUserMedia时使用有关权限的信息

再举一个例子:

navigator.mediaDevices.getUserMedia({
          video: !this.isMicrophoneAccessGranted,
          audio: !this.isCameraAccessGranted,
        })
        .then(() => {
          this.initStream();
        });

目前,此API是有限的,可能在不久的将来无法在iOS上工作……但现在不是这样,您应该能够使用audio:true和deviceid属性创建约束对象。示例:.getUserMedia{audio:true,deviceId:{exact:$deviceId.value}
const checkForVideoAudioAccess = async () => {
        try {
          const cameraResult = await navigator.permissions.query({ name: 'camera' });
          // The state property may be 'denied', 'prompt' and 'granted'
          this.isCameraAccessGranted = cameraResult.state !== 'denied';

          const microphoneResult = await navigator.permissions.query({ name: 'microphone' });
          this.isMicrophoneAccessGranted = microphoneResult.state !== 'denied';
        } catch(e) {
          console.error('An error occurred while checking the site permissions', e);
        }

        return true;
      }
navigator.mediaDevices.getUserMedia({
          video: !this.isMicrophoneAccessGranted,
          audio: !this.isCameraAccessGranted,
        })
        .then(() => {
          this.initStream();
        });