public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
int position = 0;
boolean isPaused = false; // To prevent false resume.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Play
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mediaPlayer != null) {
mediaPlayer.release();
}
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource("http://nexoft.tk/download/Davich.mp3"); // or your audio file url.
mediaPlayer.prepare();
mediaPlayer.start();
isPaused = false;
} catch (Exception e)
{
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Media player started", Toast.LENGTH_SHORT).show();
}
});
// Stop
Button button2 = findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mediaPlayer != null) {
mediaPlayer.stop();
isPaused = false;
Toast.makeText(getApplicationContext(), "Media player stopped", Toast.LENGTH_SHORT).show();
}
}
});
// Pause
Button button3 = findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
position = mediaPlayer.getCurrentPosition();
mediaPlayer.pause();
isPaused = true;
Toast.makeText(getApplicationContext(), "Media player paused at " + position / 1000 + " sec", Toast.LENGTH_SHORT).show();
}
}
});
// Resume
Button button4 = findViewById(R.id.button4);
button4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mediaPlayer != null && !mediaPlayer.isPlaying() && isPaused == true) {
mediaPlayer.start();
mediaPlayer.seekTo(position);
isPaused = false;
Toast.makeText(getApplicationContext(), "Media player resumed at " + position / 1000 + " sec", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
mediaPlayer.release();
}
}
}