How to properly release Android MediaPlayer
android, java
Solution
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.
Problem
I'm trying to add a button to my android app where it plays an MP3 when the button is tapped. I've gotten it working, but without a way to release the mediaPlayer object - therefore it keeps playing even after I leave the activity. If I initialize the MediaPlayer object outside of my react() method(what gets called when the button is pressed) it causes the app to force close when the activity is opened. But if I initialize the MediaPlayer within the react() method I then can't use mplayer.release in the onQuit() method. What am I not seeing here? ``` public void react(View view) { MediaPlayer mediaPlayer = MediaPlayer.create(ToBeOrNot.this, R.raw.achord); mediaPlayer.start(); } protected void onStop(){ mediaPlayer.release(); mediaPlayer = null; } ``` Doesn't work for obvious reasons and ``` MediaPlayer mediaPlayer = MediaPlayer.create(ToBeOrNot.this, R.raw.achord); public void react(View view) { mediaPlayer.start(); } protected void onStop(){ mediaPlayer.release(); mediaPlayer = null; } ``` Causes it to force close. Update: Here is the whole java class. ``` public class ToBeOrNot extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_to_be_or_not); } MediaPlayer mediaPlayer; public void react(View view) { mediaPlayer = MediaPlayer.create(ToBeOrNot.this, R.raw.achord); mediaPlayer.start(); } protected void onStop(){ mediaPlayer.release(); mediaPlayer = null; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. //getMenuInflater().inflate(R.menu.activity_to_be_or_not, menu); // Locate MenuItem with ShareActionProvider return true; } } ``` I think what it does is relatively self explanatory. When called, it shows some text plus a button that when tapped starts a recording playing. When someone hits the back button, it should go back to the previous activity and stop the recording. Thanks for helping me!