Search code examples
androidandroid-activityandroid-music-player

MusicPlayer Pause and Start from it the start


I am developing music application .

I want to pause the player and when I go for resume it will start it from the that point.

Music.java

public class Music {

    private static MediaPlayer mp = null;

    public static void play(Context context,int resource){
        stop(context);
        mp = MediaPlayer.create(context, resource);
        mp.setLooping(true);
        mp.start();
    }

    static void stop(Context context) {
        if(mp != null){
            mp.stop();
            mp.release();
            mp = null;
        }
    }
}

SMusicActivity

public class SMusicActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button btnplay = (Button)findViewById(R.id.play);
        btnplay.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                onResume();
            }
        });

        Button btnstop = (Button)findViewById(R.id.pause);
        btnstop.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                onPause();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        Music.play(this,R.raw.govind_bolo);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Music.stop(this);
    }
}

I want to use stop button as Pause and play . I did coding for it but as you know I didn't get perfect one ..So How can I make operation like Play and Pause into this.


Solution

  • Get rid of your static Music Facade. Use a real MediaPlayer in your activity and

    • instanciate it only once (onCreate)
    • put it to play and pause when buttons are clicked
    • check with mediaPlayer.isPlaying() that you can actually play or pause the player. There is a state diagram to respect when using this object, see the javadoc for further details of states and allowed transitions from specific states.