Skip to content

Instantly share code, notes, and snippets.

@1c7
Created May 31, 2020 04:57
Show Gist options
  • Select an option

  • Save 1c7/c28e47872ac4f810559bd4149109ad3a to your computer and use it in GitHub Desktop.

Select an option

Save 1c7/c28e47872ac4f810559bd4149109ad3a to your computer and use it in GitHub Desktop.

Revisions

  1. 1c7 created this gist May 31, 2020.
    37 changes: 37 additions & 0 deletions decodeAudioData Example.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    var init = function (url) {
    var audioCtx, fail, request, source, success;
    audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    success = function (e) {
    console.log("success", e);
    };
    fail = function (e) {
    console.log("fail", e);
    };
    source = audioCtx.createBufferSource();
    request = new XMLHttpRequest();
    request.open("GET", url, true);
    request.responseType = "arraybuffer"; // 重点
    request.onload = function () {
    var audioData;
    audioData = request.response;
    // console.log(audioData); // ArrayBuffer
    audioCtx.decodeAudioData(audioData).then(function (decodedData) {
    console.log(decodedData); // object AudioBuffer
    // console.log(decodedData.length) // 42631
    // sample rate is 48000, so duration is less then a second

    // console.log(decodedData.numberOfChannels);
    var nowBuffering = decodedData.getChannelData(0); // return a Float32Array, array of 32-bit floating point numbers

    // for (var i = 0; i < decodedData.length; i++) {
    // console.log(nowBuffering[i]); // between -1 and +1
    // }
    });
    };
    return request.send();
    };

    var url =
    "https://assets.readingeggsassets.com/activities/break_it_up/audio/us/peck-fp-2476b044.mp3";

    init(url);