I have an existing mp3 encoded audio blob(1) and a newly recodred mp3 audio data(2), I want to concatenate (1) and (2) resulting in a new mp3 blob(3) of which I will use as a source for the audio tag in my html5 player/recorder.
I'm using the ConcatenateBlobs
function to concatenate an array of blobs which the resulting blob is (3).
(3) has correct audio duration; because it has the duration of (1)+(2). Although (3) is playable but stops when the (2) part starts.
//////Concatenate blobs////////////////
(function() {
window.ConcatenateBlobs = function(blobs, type, callback) {
var buffers = [];
var index = 0;
function readAsArrayBuffer() {
if (!blobs[index]) {
return concatenateBuffers();
}
var reader = new FileReader();
reader.onload = function(event) {
buffers.push(event.target.result);
index++;
readAsArrayBuffer();
};
reader.readAsArrayBuffer(blobs[index]);
}
readAsArrayBuffer();
function concatenateBuffers() {
var byteLength = 0;
buffers.forEach(function(buffer) {
byteLength += buffer.byteLength;
});
var tmp = new Uint8Array(byteLength);
var lastOffset = 0;
buffers.forEach(function(buffer) {
// BYTES_PER_ELEMENT == 2 for Uint16Array
var reusableByteLength = buffer.byteLength;
if (reusableByteLength % 2 !== 0) {
buffer = buffer.slice(0, reusableByteLength - 1);
}
tmp.set(new Uint8Array(buffer), lastOffset);
lastOffset += reusableByteLength;
});
var blob = new Blob([tmp.buffer], {
type: type
});
callback(blob);
}
};
})();
/////////////////where i use ConcatenateBlobs function////////////////
var old_blob;
var xhr = new XMLHttpRequest();
xhr.open('GET', $('.player audio source').attr("src"), true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status === 200) {
console.log("THE NEW RECORDED TRACK = " + blob.size);
old_blob = this.response;
console.log("THE LOADED TRACK = " + old_blob.size);
ConcatenateBlobs([old_blob, blob], 'audio/mp3', function(resultingBlob) {
console.log("THE RESULTING BLOB = " + resultingBlob.size);
var url = URL.createObjectURL(resultingBlob);
console.log("THE RESULTING BLOB = " + resultingBlob.size);
$('.player audio source').attr("src", url);
audio.load();
});
}
};
xhr.send();
I want to know what's the correct way of doing this.