在Javascript中检查麦克风音量

时间:2015-10-24 19:57:50

标签: javascript html5 audio

我正在尝试制作一款需要访问用户麦克风的小游戏。我需要能够检查麦克风是否已连接,然后如果是,请检查在游戏持续时间内通过麦克风传来的声音音量。我该怎么做?

5 个答案:

答案 0 :(得分:12)

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

以下代码将根据麦克风的音量注销大约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 */
});

如果您有此数字,则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";
  }
}

为确保尽可能详细地回答此问题,我还在下面附加了我的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;
}

毕竟,您将得到类似这样的结果。 enter image description here

答案 1 :(得分:3)

以下是检测音频控件所需的代码段(来自: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/

答案 2 :(得分:3)

简单麦克风Vu Meter请参阅https://codepen.io/www-0av-com/pen/jxzxEX

在2018年检查并运行,包括Chrome浏览器中安全更新导致的错误修复。

HTML     #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v1{ 458, 525, 255, 336, 258 }; std::vector<int> v2; while ( v1.size() ) { auto m = std::min_element(v1.begin(), v1.end()); v2.push_back(*m); v1.erase(m); } for (auto v : v1) std::cout << v << " "; std::cout << "\n"; for (auto v : v2) std::cout << v << " "; std::cout << "\n"; return 0; }

CSS

<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>

JS(需要JQuery)

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

答案 3 :(得分:3)

以下是使用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>

这也意味着,它可以按需轻松启动和停止。

答案 4 :(得分:0)

我还没有检查过这个库的代码,但online demo似乎有效:

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