Search code examples
androidandroid-audiorecord

Android - Concatenate encoded mp3 data and mp3 file data


I need to create audio file that is made of audio data that comes from two different sources. One from Microphone, another from already recorded audio mp3 file.

I am converting read data from Microphone to mp3 using Lame library and writing it to FileOutputStream like this:

bytesRead = audioRecord.read(buffer, 0, minBuffer);
int bytesEncoded = androidLame.encode(buffer, buffer, bytesRead, mp3buffer);
outputStream.write(mp3buffer, 0, bytesEncoded);

And I have got InputStream (mp3 files) which I am writing into the same FileOutputStream like this:

int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int readBytes = 0;
while ((readBytes = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, readBytes);
} 

I need alternate these two sources and write only from one source at a time. And, I want the output to be in mp3 format.

Currently, these codes are working fine if I write data only from one source.

But when I, for example, first write data coming from file and stop it, and continue writing data coming from Mic, It is not working.


Solution

  • I found the reason. It turns out that to concatenate mp3 data from different sources they should have same channels and same sample rate.

    The solution was to decode mp3 files back to PCM and encode them with the same configuration I was using to encode data read from Mic.