Search code examples
androidandroid-mediaplayersoundpool

Playing two different streams (files) simultaneously with proper sync on Android


I'm using two mediaPlayer instances to send two different streams to each channel. Half the time, it works fine but sometimes there is lag between left and right channel which is clearly audible. Is there any alternative except soundpool in Android to play multiple audio files simultaneously with sync ? soundpool is not suitable for my application since audiofiles are large (approx 20 MiB each). Audiofile format in question is : FLAC.


Solution

  • I found that there're no proper in-built mixing capabilities provided by Android API. I ended up using wav files instead of FLAC and mixing them on the fly as needed. Here is a higher level description how I achieved it.

    Read both wav files and saving data part in byte array (Don't forget to strip out header bytes)

    Mix them byte by byte to generate a unified wav file

    In my use case, I just needed to mix left and right channels, but one can do all sorts of transformations as needed.

    Create a temporary file to hold mixed data

    Play the temporary file with mediaPlayer

    One can also use audioTrack to play without storing resulting byte array to temporary file but I chose to use mediaPlayer due to built in seekTo functionality.

    Hope, this approach is helpful.