Java – How to play and stop an mp3 file in an android app

androidaudioeclipsejava

I have created an app in eclipse to play and stop an mp3 file. Everything is just fine except that when I play the audio file and stop it and I want to replay it, the play btn does not wort! I was wondering if anybody can help me? Thanks in advance.
Here comes the code:

package ir.polyglotcenter.childrenmostfrequentwords;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Main extends Activity {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    //Related to the media player
    final MediaPlayer myMediaPlayer = MediaPlayer.create(Main.this, R.raw.audio);
    //Button related to play btn
    Button myButtonOne = (Button) findViewById(R.id.btn_audio);
    myButtonOne.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            myMediaPlayer.start();

        }
    });

    //Button related to stop btn
    Button myButtonTwo = (Button) findViewById(R.id.btn_stop);
    myButtonTwo.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            myMediaPlayer.stop();

        }
    });

}
}

Best Answer

if you want to start /stop sound on Button Click then use MediaPlayer.start() and MediaPlayer.pause() to pause currently playing sound which start again on start button click . and override Activity onPause to finally stop and free MediaPlayer. make changes in your code as :

onStop Button Click :

myButtonTwo.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            myMediaPlayer.pause();  //>>pause current sound
            myMediaPlayer.seekTo(0); //>> seek to start it again 

        }
    });

and override onPause method of Activity :

  @Override
   protected void onPause{
      super.onPause();
       myMediaPlayer.stop();  //>>> stop myMediaPlayer
       myMediaPlayer.release(); //>>> free myMediaPlayer
     }
Related Topic