Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Blob to Int16Array

Tags:

javascript

mp3

I have a WAV file in Blob and in order to convert it to MP3 I need to convert it to Int16Array first (to follow the example from here: https://github.com/zhuker/lamejs).

E.g.

var mp3encoder = new lamejs.Mp3Encoder(2, 44100, 128);
// instead of `var samples = new Int16Array(44100);` I want something like `var samples = new Int16Array(blob);`
var mp3Tmp = mp3encoder.encodeBuffer(samples);

Is this possible?

like image 214
Alex Netkachov Avatar asked Oct 19 '22 09:10

Alex Netkachov


1 Answers

Provided you know the data is actually a blob of 16-bit ints, then yes, it's possible:

  1. Read the Blob into an ArrayBuffer via its arrayBuffer method (the original answer had to use FileReader, but now Blob has an arrayBuffer method; see the edit history if for some reason you have to support old environments without it):

    samples.arrayBuffer()
    .then(buffer => {
        // ...
    })
    .catch(error => {
        // ...handle/report error...
    });
    
  2. View the ArrayBuffer as an Int16Array via the Int16Array constructor:

    const data = new Int16Array(buffer);
    

Now data is the array buffer from the blob viewed as an Int16Array.

Something along these lines:

samples.arrayBuffer()
.then(buffer => {
    const data = new Int16Array(buffer);
    // ...use `data` here...
})
.catch(error => {
    // ...handle/report error...
});
like image 66
T.J. Crowder Avatar answered Oct 23 '22 10:10

T.J. Crowder