试图通过javascript从音频文件中获取分贝级别

时间:2014-11-21 21:38:46

标签: javascript json audio html5-audio web-audio

我一直在看这里的信息:

Is there a way get something like decibel levels from an audio file and transform that information into a json array?

但是当我尝试在这里运行JSBin时:

<!DOCTYPE html>
<html>
  <head>
    <meta charset=utf-8 />
    <title>Get Audio Data</title>
    <link rel="stylesheet" type="text/css" href="index.css">
    <script type="text/javascript" src="music.js"></script>
  </head>
  <body>
    <div id=meter></div>
  </body>
</html>

#meter {
    width: 500px;
    height: 15px;
    margin: 2px 0;
    background: green;
    -webkit-transition;
    width .05s;
}

function() {
    var ctx = new webkitAudioContext(),
    url = 'test.mp3',
    audio = new Audio(url),
    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);

    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) + '%';
    };
};

我不确定它在做什么。谁能给我更多信息?

1 个答案:

答案 0 :(得分:3)

替换已解散的API调用后,您的代码会生成RMS输出

old    webkitAudioContext
new    


try {

    window.AudioContext = window.AudioContext ||
        window.webkitAudioContext ||
        window.mozAudioContext ||
        window.oAudioContext ||
        window.msAudioContext;

    ctx = new AudioContext();

    console.log("cool audio context established ... ctx ");

} catch (e) {

    alert("Web Audio API is not supported by this browser\n ... http://caniuse.com/#feat=audio-api");
}

old    createJavaScriptNode
new    createScriptProcessor