How to properly release Android MediaPlayer
This Worked for me well.
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = MediaPlayer.create(this, R.raw.beep_warning);
final CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox);
checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkBox.isChecked()) {
mediaPlayer.start();
mediaPlayer.setLooping(true);
}
else{
mediaPlayer.pause();
}
}
});
}
@Override
protected void onStop() {
super.onStop();
mediaPlayer.release();
}
According to Google docs, you can implement a listener in MediaPlayer
like the below example.
You can Release and Reset automatically when it's complete.
MediaPlayer mp = MediaPlayer.create(context, R.raw.sound_one);
mp.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.reset();
mp.release();
mp=null;
}
});
mp.start();
You can't initialize the mediaplayer object outside of all methods. If you do, it tries to use a context which hasn't been created yet. You need to declare it as a class variable(outside the method), and initialize it inside:
MediaPlayer mediaPlayer;
public void react(View view) {
mediaPlayer = MediaPlayer.create(ToBeOrNot.this, R.raw.achord);
mediaPlayer.start();
}
protected void onStop(){
mediaPlayer.release();
mediaPlayer = null;
}
In addition, I'd recommend reading up on variable scope in Java.