Changing data source for audio playback using existing MediaPlayer?

Alan Moore picture Alan Moore · Aug 30, 2011 · Viewed 19.1k times · Source

I'm trying to use the same media player but change the data source. Here is what I'm trying to do: 

    private MediaPlayer mMediaPlayer;

    public void pickFile1() {
       initMediaPlayer("myfile1.mp3");
    }

    public void pickFile2() {
       initMediaPlayer("myfile2.mp3");
    }

    private void initMediaPlayer(String mediafile) {
    // Setup media player, but don't start until user clicks button!
    try {
        if (mMediaPlayer == null) {
            mMediaPlayer = new MediaPlayer();
        } else {
            mMediaPlayer.reset();   // so can change data source etc.
        }
        mMediaPlayer.setOnErrorListener(this);
        AssetFileDescriptor afd = getAssets().openFd(mediafile); 
        mMediaPlayer.setDataSource(afd.getFileDescriptor());
    }
    catch (IllegalStateException e) {
        Log.d(TAG, "IllegalStateException: " + e.getMessage());
    }
    catch (IOException e) {
        Log.d(TAG, "IOException: " + e.getMessage());
    }
    catch (IllegalArgumentException e) {
        Log.d(TAG, "IllegalArgumentException: " + e.getMessage());
    }
    catch (SecurityException e) {
        Log.d(TAG, "SecurityException: " + e.getMessage());
    }

    mMediaPlayer.setOnPreparedListener(this);
    mMediaPlayer.prepareAsync(); // prepare async to not block main thread
    mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);  // Keep playing when screen goes off!
}

I just call this when I want to change to a new mediafile. It doesn't appear to be changing the data source successfully though. First question: is it possible to do it this way, or do I have to release the media player and create a new one for each new file? If it is possible, then why isn't my code working right?

Edit: well, releasing and recreating the media player isn't doing it either! It just keeps playing the same song!?!? How is that even possible? New idea -- create a different media player for each track, is that really what I have to do here? Is this a bug in Android perhaps?

Answer

Binod Singh picture Binod Singh · May 30, 2013

Make sure to stop and reset mediaplayer before changing datasource. On more important thing when you stop it calls

onCompletion

.. So do check what you are doing in this method. Then call

mplayer.setDataSource(audioPath);
mplayer.setOnPreparedListener(this);
mplayer.prepareAsync();