在 Javascript 中检查麦克风音量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33322681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:21:44  来源:igfitidea点击:

Checking microphone volume in Javascript

javascripthtmlaudio

提问by Jacob Pickens

I'm trying to make a little game that needs access to the users mic. I need to be able to check if a mic is connected, and then if so, check the volume of the sound coming through the mic through the duration of the game. How would I do this?

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

采纳答案by ioneyed

Here is the snippet needed to detect audio controls are available (pulled from: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/getUserMedia)

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

navigator.getUserMedia(constraints, successCallback, errorCallback);

Here is a sample using the getUserMedia function that will enable you access to the microphone.

下面是一个使用 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");
}

Here is a repository that demonstrates the "input volume" you desire.

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

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

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

回答by Morphasis

A slightly more detailed answer after having to work it out myself feel may help others looking here.

在不得不自己解决之后,稍微详细一点的答案可能会帮助其他人在这里看。

This following code will log out a number of approx 0 to 100 based on the microphone volume.

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

navigator.mediaDevices.getUserMedia({ audio: true, video: true })
.then(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);
  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));
    // colorPids(average);
  }
  })
  .catch(function(err) {
    /* handle the error */
});

If you have this number jquery to style blocks of color. An example function of this i have provided below but that is the easy part. Just un-comment out the color pids function.

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

function colorPids(vol) {
  let all_pids = $('.pid');
  let amout_of_pids = Math.round(vol/10);
  let elem_range = all_pids.slice(0, amout_of_pids)
  for (var i = 0; i < all_pids.length; i++) {
    all_pids[i].style.backgroundColor="#e6e7e8";
  }
  for (var i = 0; i < elem_range.length; i++) {

    // console.log(elem_range[i]);
    elem_range[i].style.backgroundColor="#69ce2b";
  }
}

To make sure this answer is as detailed as possible i have also attached my html and css below so you can just copy the js html and css if you wish to get a working example up and running.

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

html:

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:

css:

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

After all that you will end up with something like this. enter image description here

毕竟,你最终会得到这样的结果。 在此处输入图片说明

回答by www-0av-Com

Simple Microphone Vu Meter See https://codepen.io/www-0av-com/pen/jxzxEX

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

Checked and working in 2018, including bug fix caused by security update in Chrome browser.

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>

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

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 (needs JQuery)

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");
 }
}