Encode multiple PCM streams into one MP4 file

I needed to concatenate multiple WAV files into one, compressed file. After searching Android API I came up with a solution using MediaMuxer, MediaCodec and MediaFormat (available since Android API 18). The code and API is relatively simple, yet useful. Basically, you have to intilialize encoder with desired parameters and feed it with PCM input stream. The encode method can be called multiple times.

 

PCMEncoder pcmEncoder = new PCMEncoder(outputFileBitrate, outputFileSampleRate, outputFileNumberOfChannels);
pcmEncoder.setOutputPath(outputPath);
pcmEncoder.prepare();
pcmEncoder.encode(inputStream, inputStreamSampleRate);
pcmEncoder.stop();

 

Full code can be found here: https://github.com/Semantive/pcm-encoder/