Jin
Jin

Reputation: 163

How I can merge two audio files - JavaScript?

I have two audio files from RecordRTC both local & remote streams. Now I want to merge the two files into one file and upload it to the server via AJAX.

e.g. (audio1.webm) and (audio2.webm).

mediaRecorder.stopRecording(function() {
    var blob = mediaRecorder.getBlob();
    var fileName = getFileName('webm');

    var fileObject = new File([blob], fileName, {
        type: 'audio/webm'
    });

    var formData = new FormData();
        formData.append('blob', fileObject);
        formData.append('filename', fileObject.name);

    $.ajax({
        url: '{{ url('/') }}/save-audio',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        success: function(response) {
            console.log(response);
        }
    });
});

Thank you in advance.

UPDATE:

I made it this way instead of recorder.addStreams, and still I can get the recorded.

var remoteVideos = $('#remoteVideos video');
var el = [];

$.each($('#remoteVideos video'), function(index, val) {
     el[index] = val.srcObject;
});
el.push(stream);
multiMediaRecorder = new MultiStreamRecorder(el);

Upvotes: 3

Views: 9371

Answers (2)

ishan shah
ishan shah

Reputation: 603

You can use a similar library: MediaStreamRecorder. Then use MultiStreamRecorder and pass two streams as below,

recorder = new MultiStreamRecorder([localStream, remoteStream]);

You will get localStream from getUserMedia and remoteStream from onaddstream event listener.

You may want to just pass the audio tracks in the array. The rest of the things as it is. FFmpeg and file merging is not necessary.

Upvotes: 0

Jin
Jin

Reputation: 163

I got it now by doing this, as below;

function onMediaSuccess(localStream) {

            var remoteVideos = $('#remoteVideos video')[0];
            multiMediaRecorder = new MultiStreamRecorder([localStream, remoteVideos.srcObject]);
            multiMediaRecorder.ondataavailable = function (blob) {
                // POST/PUT "Blob" using FormData/XHR2
                var blobURL = URL.createObjectURL(blob);
                console.log(blobURL);
            };
            multiMediaRecorder.start();
    }

But now there's another problem, ondataavailable is called twice but the first video is playable and working properly, while the second video is playable but (less than one second) I think it might be corrupted.

Cheers!

Upvotes: 0

Related Questions