Reputation: 39
I have a very simple Android application where an audio file should start playing as soon as the app opens up.
But the audio doesn't play at all and I get this warning in Logcat: MediaPlayer finalized without being released
MainActivity.java:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaPlayer mPlayer = MediaPlayer.create(this, R.raw.song);
mPlayer.start();
}
}
I initialized MediaPlayer with the MediaPlayer.create() method, so I shouldn't have to prepare or release the mPlayer.
I'm not sure if it's a problem in my code or just a sound output problem with the android emulator.
UPDATE: I tried to declare the MediaPlayer outside of the onCreate() method and initialize it inside onCreate(). Now I don't get the warning but it still doesn't play the audio.
Updated MainActivity.java:
public class MainActivity extends AppCompatActivity {
MediaPlayer mPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlayer = MediaPlayer.create(this, R.raw.song);
mPlayer.start();
}
}
UPDATE 2: I added 3 callbacks, onPreparedListener, onErrorListener, and onCompletionListener in my application.
Updated MainActivity.java
public class MainActivity extends AppCompatActivity {
MediaPlayer mPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlayer = MediaPlayer.create(this, R.raw.song);
mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.e("Error", "onError: " + what);
return false;
}
});
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
Log.i("Completion", "onCompletion: Completed");
}
});
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
Log.i("Prepared", "onPrepared: Prepared MediaPlayer");
}
});
mPlayer.start();
}
}
I get the prepared log pretty much as soon as the app starts, and I get the completed log after I wait out the duration of my audio file. I don't get any error logs in between.
Upvotes: 0
Views: 1554
Reputation: 149
The first you must declare the class of MediaPlayer,
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.create(this, R.raw.song);
mediaPlayer.prepare();
mediaPlayer.start();
I expect this code work and helpful to everyone that read this post
Upvotes: -1