V
V
veydlin2015-10-18 03:17:19
JavaScript
veydlin, 2015-10-18 03:17:19

How to get Blob from lamejs?

I found a wonderful high-speed library https://github.com/zhuker/lamejs
But I can’t get data from it in the format Blobso that later I can just download the file:

var mp3Blob = new Blob([mp3Data], { type: 'audio/mp3' });
var url = (window.URL || window.webkitURL).createObjectURL(mp3Blob);
var link = document.getElementById("save");
link.href = url;
link.download = 'output.mp3';

And simple audio playback:
var audio = new Audio(...);
audio.play();

Here is how another library outputs buffer data via console.log, it works:
e8d264336e9f4a0caf3232dd153e343c.png
This one throws it out, it is clear that the number is negative, but you need uint8
dbd697cee504471282660e371e7a995c.png
After converting to uint8, it outputs everything zero-based
db9d858881014572a70f5dda593e443d.png
I took the example code from the repository and added example.html, this is what happened (result screenshots):
<html>
<body>Encoding mp3 from <code>testdata/Left44100.wav</code>
</body>
<script src="lame.min.js"></script>
<script>
    liblame = new lamejs();
  var mp3Data = [];
  
    function encodeMono(channels, sampleRate, samples) {
        mp3enc = new liblame.Mp3Encoder(channels, sampleRate, 128);
        var remaining = samples.length;
        var maxSamples = 1152;
        for (var i = 0; remaining >= maxSamples; i += maxSamples) {
            var mono = samples.subarray(i, i + maxSamples);
            var mp3buf = mp3enc.encodeBuffer(mono);
            if (mp3buf.length > 0) {
                mp3Data.push(mp3buf);
            }
            remaining -= maxSamples;
        }

    var mp3buf = mp3enc.flush(); //finish writing mp3
    if(mp3buf.length > 0) {
      mp3Data.push(mp3buf);
    }
    

        console.log("mp3Data ", mp3Data);
        console.log("new Uint8Array(mp3Data) ", new Uint8Array(mp3Data));
        console.log('done encoding');
    }

    var wavFile = "testdata/Left44100.wav";

    var request = new XMLHttpRequest();
    request.open("GET", wavFile, true);
    request.responseType = "arraybuffer";

    // Our asynchronous callback
    request.onload = function () {
        audioData = request.response;
        wav = liblame.WavHeader.readHeader(new DataView(audioData));
        samples = new Uint16Array(audioData, wav.dataOffset, wav.dataLen / 2);
        encodeMono(wav.channels, wav.sampleRate, samples);
    };
    request.send();
</script>
</html>

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question