4

I'm using flash to capture audio, encode it to mp3, then send it to javascript as ByteArray. Now I want the javascript to save it as MP3 on my computer (not flash saves it to my computer). I am using Blob and then getDataURL, but the file isn't playing when saved. I used to do the same exact method to save WAV files and it worked perfectly fine. Here's the JS code:

var getDataFromSWF = function (bytes) {
            var myBlob = new Blob([bytes], { type: "audio/mpeg3" });

            var url = (window.URL || window.webkitURL).createObjectURL(myBlob);
            var link = window.document.createElement('a');
            link.href = url;

//            $("label").text(url);
            link.download = 'output.mp3';
            var click = document.createEvent("Event");
            click.initEvent("click", true, true);
            link.dispatchEvent(click);

//            console.log(bytes);
        }

I'm pretty much sure that the byteArray is fine because if I let the SWF save the file it works OK too. But I want to know what's wrong with the JS code. (note: i'm new to BLOB)

1 Answer 1

1

Try this to get the Blob

function base64toBlob(base64Data, contentType) {
    var sliceSize = 1024;
    var byteCharacters = atob(base64Data);
    var bytesLength = byteCharacters.length;
    var slicesCount = Math.ceil(bytesLength / sliceSize);
    var byteArrays = new Array(slicesCount);
    for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        var begin = sliceIndex * sliceSize;
        var end = Math.min(begin + sliceSize, bytesLength);
        var bytes = new Array(end - begin);
        for (var offset = begin, i = 0 ; offset < end; ++i, ++offset) {
            bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
    }
    return new Blob(byteArrays, { type: contentType });
}
Sign up to request clarification or add additional context in comments.

1 Comment

I was sending byte array and was receiving base64 as response content - nothing worked but this - thanks much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.