1

I have two byte arrays. One contains background music and the second contains recorded voice.

How could I combine them into single array and play that with a MediaPlayer?

I was trying to do next:

1)

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
if (array1 != null && array1 != 0) 
outputStream.Write(array1); 
if (array2 != null && array2 != 0) 
outputStream.Write(array2); 
return outputStream.ToByteArray();

2)

byte[] joinedArray = Arrays.CopyOf(array1, array1.Length + array2.Length); 
Array.Copy(array2, 0, joinedArray, array1.Length, array2.Length);
return joinedArray;

In both cases I receive not merged array (only voice or only music is played if I pass that to the MediaPlayer).

Thanks in advance.

Bogdan
  • 107
  • 9

1 Answers1

1

In both cases I receive not merged array (only voice or only music is played if I pass that to the MediaPlayer)

You could refer to this question: C# : concatenate 2 MP3 files. As @Matthew Whited said:

You are copying the second song data over the first. And MP3 data is streaming so you can just append the files to each other without worrying about bitrates (while they may glitch) the bitrate should automatically adjust.

Try using the following code:

using (var fs = File.OpenWrite(Path.Combine(path, "3.mp3")))
{
    var buffer = File.ReadAllBytes(Path.Combine(path, "1.mp3"));
    fs.Write(buffer, 0, buffer.Length);
    buffer = File.ReadAllBytes(Path.Combine(path, "2.mp3"));
    fs.Write(buffer, 0, buffer.Length);
    fs.Flush();
}

Update:

Consider two cases for .mp3 files:

  • Files with same sampling frequency and number of channels

In this case, we can just append the second file to end of first file. This can be achieved using File classes available on Android.

  • Files with different sampling frequency or number of channels.

In this case, one of the clips has to be re-encoded to ensure both files have same sampling frequency and the number of channels. To do this, we would need to decode MP3, get PCM samples, process it to change sampling frequency and then re-encode to MP3.

Android does not have transcode or reencode APIs. One option is to use an external library like lame/FFMPEG via JNI for re-encoding.

York Shen
  • 9,014
  • 1
  • 16
  • 40
  • Following code could be useful if I have an access to files. But in my case I have only two arrays. `Array.Copy(files[0], 0, a, 0, files[0].Length);` `Array.Copy(files[1], 0, a, files[0].Length, files[1].Length);` From that post I've tried this code but in result I still receive only voice or only music. Any ideas? – Bogdan Feb 20 '18 at 10:30