Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read samples from wav-file

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!

like image 958
myName Avatar asked Mar 28 '15 13:03

myName


1 Answers

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.

like image 65
Touffy Avatar answered Oct 17 '22 05:10

Touffy