Read samples from wav-file

自作多情 提交于 2019-12-09 10:50:00

问题


I'm trying to make a webpage in html5 which stores sample-data from a wav-file in an array. Is there any way to get the sample-data with javascript? I'm using a file-input to select the wav-file.

In the javascript I already added:

document.getElementById('fileinput').addEventListener('change', readFile, false);

but I have no idea what to do in readFile.

EDIT: I tried to get the file in an ArrayBuffer, pass it to the decodeAudioData method and get a typedArraybuffer out of it. This is my code:

var openFile = function(event) {
var input = event.target;
var audioContext = new AudioContext();

var reader = new FileReader();
reader.onload = function(){
var arrayBuffer = reader.result;
  console.log("arrayBuffer:");
  console.log(arrayBuffer);
  audioContext.decodeAudioData(arrayBuffer, decodedDone);

};
reader.readAsArrayBuffer(input.files[0]);
};
function decodedDone(decoded) {
var typedArray = new Uint32Array(decoded, 1, decoded.length);
  console.log("decoded");
  console.log(decoded);
  console.log("typedArray");
  console.log(typedArray);

for (i=0; i<10; i++)
{
    console.log(typedArray[i]);
}

}

The elements of typedArray are all 0. Is my way of creating the typedArray wrong or did I do something else wrong on?

EDIT: I finally got it. This is my code:

var openFile = function(event) {
var input = event.target;
var audioContext = new AudioContext();

var reader = new FileReader();
reader.onload = function(){
var arrayBuffer = reader.result;
  console.log("arrayBuffer:");
  console.log(arrayBuffer);
  audioContext.decodeAudioData(arrayBuffer, decodedDone);

};
reader.readAsArrayBuffer(input.files[0]);
};
function decodedDone(decoded) {

 var typedArray = new Float32Array(decoded.length);

typedArray=decoded.getChannelData(0);
console.log("typedArray:");
console.log(typedArray);

}

Thanks for the answers!


回答1:


You'll need to learn a lot about Web APIs to accomplish that, but in the end it's quite simple.

  1. Get the file contents in an ArrayBuffer with the File API
  2. Pass it to the Web Audio API's decodeAudioData method.
  3. Get a typed ArrayBuffer with the raw samples you wanted.

Edit: If you want to implement an equalizer, you're wasting your time, there's a native equalizer node in the Audio API. Depending on the length of your wave file it might be better not to load it all in memory and instead to just create a source that reads from it and connect that source to an equalizer node.



来源:https://stackoverflow.com/questions/29317866/read-samples-from-wav-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!