Created
May 31, 2020 04:57
-
-
Save 1c7/c28e47872ac4f810559bd4149109ad3a to your computer and use it in GitHub Desktop.
decodeAudioData Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
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
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
Note
I am just too lazy to edit MDN and add this as example code.
Hope this public gist help. (someone Google keyword "decodeAudioData" and found this)
This code originally come from CodePen, and I just modify a few lines