How to play and stop an mp3 file in an android app
22,279
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
}
Author by
Behzad Moradi
Updated on July 09, 2022Comments
-
Behzad Moradi almost 2 years
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(); } }); } }
-
Behzad Moradi about 11 yearsThanks a lot for helping me
-
Tapa Save almost 10 yearsThis in can't play mp3 from any part, 'sdcasd/1.mp3' for example.