开发者

Android MediaPlayer - only one instance at any given time?

I have a audio player app, where there is a Main activity that shows 3 audio sample urls. On click on one, it goes to a Details Activity, which has a play and pause button, to start and pause the audio.

My problem is that, when I st开发者_StackOverflow中文版art the Main activity, and say click on audio 1, I hit play on Details activity. This starts the MediaPlayer and the audio starts to play. When I go back to the Main activity, the audio is still playing, which is what I want. Now, when I click on audio 1 again, and go to Details Activity and hit play again, there seems to be a new MediaPlayer starting the audio. So I have 2 tracks playing together!

Is there a way I can have only one MediaPlayer instance at any given time?

Thanks Chris


You should consider the Singleton pattern. Make a class MyPlayer that has a static method getMediaPlayer() that returns the same instance of MediaPlayer each time called.


Singleton Class

public final class MySingleton extends Application {

     static MediaPlayer instance;

    public static MediaPlayer getInstance() {

        if (instance == null)
        {
            instance = new MediaPlayer();

        }


        return instance;
    }


}

Adapter Where your List

Initialize Your Singleton Class One time in Constructor

private static MediaPlayer mMediaPlayer = MySingleton.getInstance();

if (mMediaPlayer.isPlaying()) {
 try {
  mMediaPlayer.reset();
  mMediaPlayer.stop();

  mMediaPlayer.setDataSource(mainActivity, Uri.parse(songsarraylist.get(position).getPath()));
  mMediaPlayer.prepare();
  mMediaPlayer.start();




 } catch (Exception e) {
  Toast.makeText(mainActivity, "Catching", Toast.LENGTH_SHORT).show();
 }


} else {
 try {

  mMediaPlayer.setDataSource(mainActivity, Uri.parse(songsarraylist.get(position).getPath()));
  mMediaPlayer.prepare();
  mMediaPlayer.start();
 } catch (IOException e) {
  e.printStackTrace();
 }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜