Skip to content

Instantly share code, notes, and snippets.

@1c7
Created May 31, 2020 04:57
Show Gist options
  • Save 1c7/c28e47872ac4f810559bd4149109ad3a to your computer and use it in GitHub Desktop.
Save 1c7/c28e47872ac4f810559bd4149109ad3a to your computer and use it in GitHub Desktop.
decodeAudioData Example
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);
@1c7
Copy link
Author

1c7 commented May 31, 2020

Tips

for (var i = 0; i < decodedData.length; i++) {
  console.log(nowBuffering[i]);
}

is extremely slow and possiblly would freeze up your browser
because It need to output 42631 values

@1c7
Copy link
Author

1c7 commented May 31, 2020

What is this?

It read an audio file, and output raw PCM data.

I need to draw waveform, so I am experiemnting with these.

Also, this blog post is very helpful:
https://matt.aimonetti.net/posts/2019-06-generating-waveform-data-audio-representation/

it help you understand the fundemental behind drawing waveform

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment