【问题标题】:How do you get the decibel level of an audio in Javascript你如何在Javascript中获得音频的分贝级别
【发布时间】:2015-03-23 07:06:25
【问题描述】:

我目前正在使用 JavaScript、HTML 和 CSS 制作分贝计可视化工具。

我已经阅读了几个 Web Audio API 教程,但其中没有任何内容能具体说明我想要做什么。

这是我目前所拥有的:

window.onload = init;

function init() {
  
  var ctx = new webkitAudioContext()
    , url = 'https://dl.dropboxusercontent.com/u/86176287/pbjt.mp3'  
    , audio = new Audio(url)
    // 2048 sample buffer, 1 channel in, 1 channel out  
    , processor = ctx.createJavaScriptNode(2048, 1, 1)
    , meter = document.getElementById('meter')
    , source;
    
  audio.addEventListener('canplaythrough', function(){
    source = ctx.createMediaElementSource(audio);
    source.connect(processor);
    source.connect(ctx.destination);
    processor.connect(ctx.destination);
    audio.play();
  }, false);
  
  // loop through PCM data and calculate average
  // volume for a given 2048 sample buffer
  processor.onaudioprocess = function(evt){
    var input = evt.inputBuffer.getChannelData(0)
      , len = input.length   
      , total = i = 0
      , rms;
    while ( i < len ) total += Math.abs( input[i++] );
    rms = Math.sqrt( total / len );
    meter.style.width = ( rms * 100 ) + '%';
  };
  
}

有人可以解释一下我需要做什么,或者指出正确的方向吗,因为这似乎不起作用?

【问题讨论】:

  • 什么不起作用?您的值 rms 是您期望的值(介于 -1 和 1 之间)还是只需要公式来转换为 dB?
  • 您好,代码现在可以正常工作了吗?如果是这样,请将其作为答案发布,以便可以将问题标记为已解决。谢谢!
  • @ipalibowhyte 您可以添加与问题分开的自己的答案,并将其标记为已接受的答案。
  • @CTS_AE 看来 OP 已经意识到了——他们以前做过。此外,OP 已停用 1.5 年

标签: javascript audio html5-audio decibel


【解决方案1】:

固定

所以我把它改成这样:

var audioCtx = new AudioContext();
var url = 'https://dl.dropboxusercontent.com/u/86176287/pbjt.mp3';
var audio = new Audio(url);
var processor = audioCtx.createScriptProcessor(2048, 1, 1);
var meter = document.getElementById('meter');
var source;

audio.addEventListener('canplaythrough', function(){
source = audioCtx.createMediaElementSource(audio);
source.connect(processor);
source.connect(audioCtx.destination);
processor.connect(audioCtx.destination);
//audio.play();
}, false);

// loop through PCM data and calculate average
// volume for a given 2048 sample buffer
processor.onaudioprocess = function(evt){
var input = evt.inputBuffer.getChannelData(0)
  , len = input.length   
  , total = i = 0
  , rms;
while ( i < len ) total += Math.abs( input[i++] );
rms = Math.sqrt( total / len );
//console.log(( rms * 100 ));
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-04
    • 2013-08-28
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多