【问题标题】:Checking microphone volume in Javascript在 Javascript 中检查麦克风音量
【发布时间】:2015-10-24 19:57:50
【问题描述】:

我正在尝试制作一个需要访问用户麦克风的小游戏。我需要能够检查是否连接了麦克风,如果连接了,请检查游戏期间通过麦克风发出的声音的音量。我该怎么做?

【问题讨论】:

  • 两个原始答案指的是一个不再有效的样本(对我来说),所以我添加了一个新答案stackoverflow.com/a/50279260/1863152,其中包括一个带有数字和视觉输出的麦克风 vu 表。

标签: javascript html audio


【解决方案1】:

在自己想出来之后稍微详细一点的答案可能会帮助其他人在这里查看。

以下代码将根据麦克风音量注销大约 0 到 100 的数字。

navigator.mediaDevices.getUserMedia({
  audio: true,
  video: true
})
  .then(function(stream) {
    const audioContext = new AudioContext();
    const analyser = audioContext.createAnalyser();
    const microphone = audioContext.createMediaStreamSource(stream);
    const scriptProcessor = audioContext.createScriptProcessor(2048, 1, 1);

    analyser.smoothingTimeConstant = 0.8;
    analyser.fftSize = 1024;

    microphone.connect(analyser);
    analyser.connect(scriptProcessor);
    scriptProcessor.connect(audioContext.destination);
    scriptProcessor.onaudioprocess = function() {
      const array = new Uint8Array(analyser.frequencyBinCount);
      analyser.getByteFrequencyData(array);
      const arraySum = array.reduce((a, value) => a + value, 0);
      const average = arraySum / array.length;
      console.log(Math.round(average));
      // colorPids(average);
    };
  })
  .catch(function(err) {
    /* handle the error */
    console.error(err);
  });

如果你有这个数字 jquery 来设置颜色块的样式。我在下面提供了一个示例功能,但这是最简单的部分。只需取消注释掉 颜色 pids 函数。

function colorPids(vol) {
  const allPids = [...document.querySelectorAll('.pid')];
  const numberOfPidsToColor = Math.round(vol / 10);
  const pidsToColor = allPids.slice(0, numberOfPidsToColor);
  for (const pid of allPids) {
    pid.style.backgroundColor = "#e6e7e8";
  }
  for (const pid of pidsToColor) {
    // console.log(pid[i]);
    pid.style.backgroundColor = "#69ce2b";
  }
}

为了确保这个答案尽可能详细,我还在下面附上了我的 html 和 css,因此如果您希望启动并运行一个工作示例,您可以复制 js html 和 css。

html:

<div class="pids-wrapper">
  <div class="pid"></div>
  <div class="pid"></div>
  <div class="pid"></div>
  <div class="pid"></div>
  <div class="pid"></div>
  <div class="pid"></div>
  <div class="pid"></div>
  <div class="pid"></div>
  <div class="pid"></div>
  <div class="pid"></div>
</div>

css:

.pids-wrapper{
  width: 100%;
}
.pid{
  width: calc(10% - 10px);
  height: 10px;
  display: inline-block;
  margin: 5px;
}

毕竟你最终会得到这样的东西。

【讨论】:

  • 使用此代码时,音量会超过 100,有时甚至会高于 200。知道如何精确到 0-100 之间吗??
  • 如何连接特定的音频设备?
  • 如何使它适用于特定设备而不是默认的内置扬声器?
  • 请注意,createScriptProcessor 自 2014 年以来已被弃用,取而代之的是 AudioWorklet,很高兴看到更新的示例
  • @mrossman 我已经用setTimeout 写了一个更新的answer
【解决方案2】:

这是一个简单地使用setTimeout 而不是已弃用的createScriptProcessor 函数的答案:

(async () => {
  let volumeCallback = null;
  let volumeInterval = null;
  const volumeVisualizer = document.getElementById('volume-visualizer');
  const startButton = document.getElementById('start');
  const stopButton = document.getElementById('stop');
  // Initialize
  try {
    const audioStream = await navigator.mediaDevices.getUserMedia({
      audio: {
        echoCancellation: true
      }
    });
    const audioContext = new AudioContext();
    const audioSource = audioContext.createMediaStreamSource(audioStream);
    const analyser = audioContext.createAnalyser();
    analyser.fftSize = 512;
    analyser.minDecibels = -127;
    analyser.maxDecibels = 0;
    analyser.smoothingTimeConstant = 0.4;
    audioSource.connect(analyser);
    const volumes = new Uint8Array(analyser.frequencyBinCount);
    volumeCallback = () => {
      analyser.getByteFrequencyData(volumes);
      let volumeSum = 0;
      for(const volume of volumes)
        volumeSum += volume;
      const averageVolume = volumeSum / volumes.length;
      // Value range: 127 = analyser.maxDecibels - analyser.minDecibels;
      volumeVisualizer.style.setProperty('--volume', (averageVolume * 100 / 127) + '%');
    };
  } catch(e) {
    console.error('Failed to initialize volume visualizer, simulating instead...', e);
    // Simulation
    //TODO remove in production!
    let lastVolume = 50;
    volumeCallback = () => {
      const volume = Math.min(Math.max(Math.random() * 100, 0.8 * lastVolume), 1.2 * lastVolume);
      lastVolume = volume;
      volumeVisualizer.style.setProperty('--volume', volume + '%');
    };
  }
  // Use
  startButton.addEventListener('click', () => {
    // Updating every 100ms (should be same as CSS transition speed)
    if(volumeCallback !== null && volumeInterval === null)
      volumeInterval = setInterval(volumeCallback, 100);
  });
  stopButton.addEventListener('click', () => {
    if(volumeInterval !== null) {
      clearInterval(volumeInterval);
      volumeInterval = null;
    }
  });
})();
div {
  --volume: 0%;
  position: relative;
  width: 200px;
  height: 20px;
  margin: 50px;
  background-color: #DDD;
}

div::before {
   content: '';
   position: absolute;
   top: 0;
   bottom: 0;
   left: 0;
   width: var(--volume);
   background-color: green;
   transition: width 100ms linear;
}

button {
  margin-left: 50px;
}

h3 {
  margin: 20px;
  font-family: sans-serif;
}
<h3><b>NOTE:</b> This is not accurate on stackoverflow, since microphone use is not permitted. It's a simulation instead.</h3>
<div id="volume-visualizer"></div>
<button id="start">Start</button>
<button id="stop">Stop</button>

这也意味着,它可以很容易地按需启动和停止。

【讨论】:

    【解决方案3】:

    这里是检测音频控件所需的 sn-p 可用(来自:https://developer.mozilla.org/en-US/docs/Web/API/Navigator/getUserMedia

    navigator.getUserMedia(constraints, successCallback, errorCallback);
    

    这是一个使用 getUserMedia 函数的示例,可让您访问麦克风。

    navigator.getUserMedia = navigator.getUserMedia ||
                         navigator.webkitGetUserMedia ||
                         navigator.mozGetUserMedia;
    
    if (navigator.getUserMedia) {
       navigator.getUserMedia({ audio: true, video: { width: 1280, height: 720 } },
          function(stream) {
             console.log("Accessed the Microphone");
          },
          function(err) {
             console.log("The following error occured: " + err.name);
          }
        );
    } else {
       console.log("getUserMedia not supported");
    }
    

    这是一个展示您想要的“输入量”的存储库。

    https://github.com/cwilso/volume-meter/

    【讨论】:

    • 非常感谢。这真的很有帮助!
    • OP 说check the volume of the sound coming through the mic。我看不出这个答案如何帮助实现这一目标..
    • 他最初的问题是看看mic is connected 如果连接到check the volume of the sound coming through the mic,我提供了一个存储库来证明这一点(你也提供了)。
    • 看起来这在 Firefox 中有效,但在 Chrome 中无效(Chrome 中没有绘制音量计)。
    【解决方案4】:

    简单的麦克风音量计见https://codepen.io/www-0av-com/pen/jxzxEX

    在 2018 年检查并正常工作,包括由 Chrome 浏览器中的安全更新引起的错误修复。

    HTML <h3>VU meter from mic input (getUserMedia API)</h3> <button onclick="startr();" title="click start needed as security in browser increased and voice mic can only be started from a gesture on page">Start</button> <canvas id="canvas" width="150" height="300" style='background:blue'></canvas> <br> CLICK START <div align=left>See JS for attribution</div>

    CSS

    body {
      color: #888;
      background: #262626;
      margin: 0;
      padding: 40px;
      text-align: center;
      font-family: "helvetica Neue", Helvetica, Arial, sans-serif;
    }
    
    #canvas {
      width: 150px;
      height: 100px;
      position: absolute;
      top: 150px;
      left: 45%;
      text-align: center;
    }
    

    JS(需要 JQuery)

    // Courtesy www/0AV.com, LGPL license or as set by forked host, Travis Holliday, https://codepen.io/travisholliday/pen/gyaJk 
    function startr(){
     console.log ("starting...");
     navigator.getUserMedia = navigator.getUserMedia ||
       navigator.webkitGetUserMedia ||
       navigator.mozGetUserMedia;
     if (navigator.getUserMedia) {
      navigator.getUserMedia({
          audio: true
        },
        function(stream) {
          audioContext = new AudioContext();
          analyser = audioContext.createAnalyser();
          microphone = audioContext.createMediaStreamSource(stream);
          javascriptNode = audioContext.createScriptProcessor(2048, 1, 1);
    
          analyser.smoothingTimeConstant = 0.8;
          analyser.fftSize = 1024;
    
          microphone.connect(analyser);
          analyser.connect(javascriptNode);
          javascriptNode.connect(audioContext.destination);
    
          canvasContext = $("#canvas")[0].getContext("2d");
    
          javascriptNode.onaudioprocess = function() {
              var array = new Uint8Array(analyser.frequencyBinCount);
              analyser.getByteFrequencyData(array);
              var values = 0;
    
              var length = array.length;
              for (var i = 0; i < length; i++) {
                values += (array[i]);
              }
    
              var average = values / length;
    
    //          console.log(Math.round(average - 40));
    
              canvasContext.clearRect(0, 0, 150, 300);
              canvasContext.fillStyle = '#BadA55';
              canvasContext.fillRect(0, 300 - average, 150, 300);
              canvasContext.fillStyle = '#262626';
              canvasContext.font = "48px impact";
              canvasContext.fillText(Math.round(average - 40), -2, 300);
              // console.log (average);
            } // end fn stream
        },
        function(err) {
          console.log("The following error occured: " + err.name)
        });
    } else {
      console.log("getUserMedia not supported");
     }
    }
    

    【讨论】:

    • 知道如何让它在 safari 上运行吗?或者为什么没有?
    • @Ann,我猜我会说这是因为它处理的 I/O 在不同的操作系统上完全不同。例如:Linux 通常运行在与 MS 兼容的硬件上,所以我想这适用于 MS 或 Linux 下的 Chrome 风格的浏览器,但 Apple 的硬件完全不同。遗憾的是我没有时间研究它(此外,你没有提到它是 iPhone/iPad 还是 Mac),但我会从谷歌搜索“audioContext.createMediaStreamSource not working on safari”开始......这立即证实你并不孤单对我来说。
    • @Ann For Safari 而不是audioContext = new AudioContext();audioContext = new (window.AudioContext || window.webkitAudioContext)();
    猜你喜欢
    • 1970-01-01
    • 2020-11-14
    • 2011-09-05
    • 2013-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    相关资源
    最近更新 更多