Search code examples
androidaudiomedia-player

Unable to play two MediaPlayer at same time in Nexus 5


I am trying to play some audio in background using two MediaPlayers inside a Service. Everything works fine if I want to play only one mp3, but If I try to play two at the same time, using two instances of MediaPlayer, only the last one works. It is weird because it works in emulator and some devices, but I am unable to make it work in a Nexus 5. This is the code I am using to create the two MediaPlayer instances:

private void playWithPiano() {
    mp1 = initializePlayer(filenameVoz); // filenameVoz is the mp3 file name in raw folder
    mp2 = initializePlayer("base_piano");
    mp1.start();
    mp2.start();
}

private MediaPlayer initializePlayer(String filename) {
    int identifier = getResources().getIdentifier(filename,
            "raw", getPackageName());
    MediaPlayer mp = MediaPlayer.create(this, identifier);

    mp.setOnErrorListener(new OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            Log.d(TAG_LOG, "OnErrorListener");
            stop();

            return false;
        }
    });
    mp.setOnCompletionListener(new OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            stop();
        }
    });

    return mp;
}

If I comment the mp2.start line, then I can listen the mp1 audio. It is like when a MediaPlayer is started, any other instances are stopped I would appreciate any help with this.


Solution

  • I found other posts describing the same problem in Nexus 5 devices, but don't have a solution yet. https://code.google.com/p/android/issues/detail?id=63099 https://code.google.com/p/android/issues/detail?id=62304 I tried using seekTo(0) like it was suggested in one of those forums, but it didn't work, so I tried another thing that seems like an specific workaround for my case.

    I am using this inside a Service, and my second MediaPlayer is only to play some background music, so I started it half second after the first one and it worked.

    new java.util.Timer().schedule( 
                    new java.util.TimerTask() {
                        @Override
                        public void run() {
                            if (mp2 != null) mp2.start();
                        }
                    }, 
                    500
            );
    

    I still don't know why I am having this problem only in the Nexus 5, but I hope this may help somebody.