getUserMedia引发异常:TypeError:navigator.getUserMedia不是函数

问题描述

我正在尝试使用纯JavaScript构建吉他调音器。我需要访问用户的麦克风。为此,我曾经能够使用Navigator.getUserMedia(),但是现在不建议使用,并且任何现代浏览器均不支持。我以前使用的代码看起来像这样

function getUserMedia(dictionary,callback) {
    try {
        navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia; navigator.getUserMedia(dictionary,callback,error);
    } catch (e) {
        alert('getUserMedia threw exception :' + e);
    }
}

function gotStream(stream) {
    // Create an AudioNode from the stream.
    mediastreamsource = audioContext.createmediastreamsource(stream);

    // Connect it to the destination.
    analyser = audioContext.createAnalyser();
    analyser.fftSize = 2048;
    mediastreamsource.connect( analyser );
    updatePitch();
}

function toggleLiveinput() {
    if (isPlaying) {
        //stop playing and return
        sourceNode.stop( 0 );
        sourceNode = null;
        analyser = null;
        isPlaying = false;
        if (!window.cancelAnimationFrame)
            window.cancelAnimationFrame = window.webkitCancelAnimationFrame;
        window.cancelAnimationFrame( rafID );
    }
    getUserMedia(
        {
            "audio": {
                "mandatory": {
                    "googEchoCancellation": "false","googAutoGainControl": "false","googNoiseSuppression": "false","googHighpassFilter": "false"
                },"optional": []
            },},gotStream);
}

如果我使用此方法,则会抛出错误,因为它不受支持

MDN建议改为使用MediaDevices.getUserMedia(),但我不知道如何转换现有代码以使用此代码

在这里Firefox: navigator.getUserMedia is not a function找到了另一个相似的问题/答案,因此我将功能更改为

async function getMedia(pc) {
  let stream = null;

  try {
    stream = await navigator.mediaDevices.getUserMedia(constraints);
    /* use the stream */
  } catch(err) {
    /* handle the error */
      alert('getUserMedia threw exception :' + err);
  }
}

并将呼叫从getUserMedia更改为getMedia

现在它引发新错误“ TypeError:无法读取未定义的属性'getUserMedia'”

有人可以告诉我如何在现有代码中使用新的navigator.mediaDevices.getUserMedia方法吗?我想我只是缺少明显的东西。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)