I am having an odd issue where my audio file sometimes plays and sometimes does not play. The catch is that when it decides to not play, the DDMS gives me an:
This should fix your problem (did for me): Replace the line that says "player.start()" following the rest of your code with an async callback like so:
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
This error is just a Log.e, not a real error. It shouldn't cause your player to not play, I'm guessing it's just because the player hadn't finished preparing when you try to call start().
E/MediaPlayer﹕ Should have subtitle controller already set
set in manifest file may help you
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Looking at a previous discussion on StackOverflow, and the referenced Android commit where this was introduced, the code above might not completely initialize the MediaPlayer
object.
The KitKat example code for media playback suggests that you should call:
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
immediately after you construct the MediaPlayer
, and before you call its setDataSource
method.
I had the same issue and I fixed it by adding the following right after instantiating MediaPlayer.
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
if (mp == mediaPlayer) {
mediaPlayer.start();
}
}
});
Previously I was implementing MediaPlayer.OnPreparedListener and overriding onPrepared() but it didn't work.
I hope this helps!
Its been a long time since I was working on this app. Here is what I ended up doing to get this to work. (Tested on KitKat and Lollipop). I think switching from MediaPlayer to APMediaPlayer was part of the trick.
@Override
public void onDestroy() {
if(player != null) {
player.release();
player = null;
}
super.onDestroy();
}
@Override
public void onStart() {
super.onStart();
if(player != null) {
player.start();
}
else {
player = new APMediaPlayer(this); //create new APMediaPlayer
player.setMediaFile("Theme.mp3"); //set the file (files are in data folder)
player.start(); //start play back
player.setLooping(true); //restart playback end reached
player.setVolume(1, 1); //Set left and right volumes. Range is from 0.0 to 1.0
}
}
@Override
public void onResume() {
super.onResume();
if(player != null) {
player.start();
}
}