Im implemented my music player function and sometimes the ogg files throws the (1,-1010) thats means
MEDIA_ERROR_UNKNOWN/ MEDIA_ERROR_MALFORMED
error. There is nothing wrong with file format because sometimes the file loading correcly (lets say 70% correcly 30% got that error).
private void loadAudio(){
if(!readyToPlay){
elapsedTimeStart.setText("");
elapsedTimeEnd.setText(context.getString(R.string.loading));
mediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaplayer.setDataSource(audioURL);
mediaplayer.prepareAsync();
mediaplayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
double ratio = percent / 1000.0;
bufferingLevel = (int)(mp.getDuration() * ratio);
seekBar.setSecondaryProgress(bufferingLevel/SECOND);
}
});
mediaplayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.i("lang","on error " +what +" extra "+ extra);
switch (what) {
case MEDIA_ERROR_UNKNOWN:
Log.i(TAG, "MEDIA_ERROR_UNKNOWN");
break;
case MEDIA_ERROR_SERVER_DIED:
Log.i(TAG, "MEDIA_ERROR_SERVER_DIED");
Toast.makeText(context, context.getString(R.string.problems_connecting_try_again), Toast.LENGTH_SHORT).show();
break;
}
switch (extra) {
case MEDIA_ERROR_IO:
Log.i(TAG, "MEDIA_ERROR_IO");
break;
case MEDIA_ERROR_MALFORMED:
Log.i(TAG, "MEDIA_ERROR_MALFORMED");
break;
case MEDIA_ERROR_UNSUPPORTED:
Log.i(TAG, "MEDIA_ERROR_UNSUPPORTED");
break;
case MEDIA_ERROR_TIMED_OUT:
Log.i(TAG, "MEDIA_ERROR_TIMED_OUT");
Toast.makeText(context, context.getString(R.string.problems_connecting_try_again), Toast.LENGTH_SHORT).show();
break;
}
return false;
}
});
mediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
Log.i("lang", " SUCCEFULLY PREPARED");
readyToPlay = true;
durationTime = mp.getDuration();
durationHour = durationTime /HOUR;
durationMint = (durationTime %HOUR)/MINUTE;
durationSec = (durationTime %MINUTE)/SECOND;
elapsedTimeStart.setText(String.format("%02d:%02d:%02d",currentHour,currentMin,currentSec));
elapsedTimeEnd.setText(String.format("%02d:%02d:%02d", durationHour, durationMint, durationSec));
seekBar.setMax(durationTime /SECOND);
play();
}
});
} catch (IllegalArgumentException|SecurityException|IllegalStateException|IOException e) {
Log.i("lang","Exception!");
e.printStackTrace();
}
catch (Exception e){
Log.i("lang", "Exception!! smthing goes wrong ");
e.printStackTrace();
}
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mediaplayer != null && fromUser) {
timeElapsed = durationTime * progress / 100;
mediaplayer.seekTo(timeElapsed);
if (durationTime / SECOND == timeElapsed / SECOND)
stop();
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}}
EDIT: I debug my program and the first callback which trigger after mediaplayer.prepareAsync() is onPrepared method. Is there a way to check when the (MEDIA_ERROR_UNKNOWN/ MEDIA_ERROR_MALFORMED) occurs on this state and recall loadAudio() function to get correct track?
There is problem with URL, the URL is incorrect or the server not sending proper response by this URL.
Thats why this URL give this Error MEDIA_ERROR_MALFORMED
EDIT
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
LogUtils.e(TAG, "onError() called : what=="+what);
LogUtils.e(TAG, "onError() called : extra=="+extra);
return false;
}
});
Related
I have some problems with my Mediaplayer. It works well, but at some mysterious circumstances it stops playing. So i put some logs in onCompletion and onError callbacks and surround it with try/catch, but when it stops none of thees logs are triggering. So my question is how can Mediaplayer stops playing and dont trigger this logs.
P.S. it plays in service, but i checked - service continue running, and also i tried to play it in singleton class and GCMService too - it still stops and i can't figure out why.
Here is my code.
public class AlertService extends Service {
private boolean isPlaying = false;
private MediaPlayer mp;
private final String TAG = "Alert_playing";
public static final String PLAY_ALERT_ACTION = "play_alert_service";
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent!=null&&intent.getAction().equals(PLAY_ALERT_ACTION)){
playAlertSound();
}
return START_NOT_STICKY;
}
public void playAlertSound() {
if (!isPlaying) {
isPlaying = true;
Log.d(TAG, "isPlaying: " + String.valueOf(isPlaying));
mp = new MediaPlayer();
Uri ringtone = Uri.parse("android.resource://" + RetailerApplication.getAppContext().getPackageName() + "/" + R.raw.alert);
try {
mp.setDataSource(RetailerApplication.getAppContext(), ringtone);
mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
isPlaying = false;
stopSelf();
Log.d(TAG, "isPlaying: " + String.valueOf(isPlaying));
}
});
}
});
mp.prepareAsync();
mp.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
isPlaying = false;
stopSelf();
Log.d(TAG, "what: " + what + " extra: " + extra);
Log.d(TAG, "isPlaying: " + String.valueOf(isPlaying));
return false;
}
});
} catch (IOException e) {
isPlaying = false;
stopSelf();
Log.d(TAG, "isPlaying: " + String.valueOf(isPlaying));
Log.d(TAG, "exception" + e);
Logger.e(TAG, e);
}
} else {
Log.d(TAG, "miss");
}
}
}
I'm trying to make a simple audio recorder. The problem with the audio recorder is that,every time the progress bar gets faster. It would run fine on the first turn, but if you cancel the audio and want to go the second time, it gets faster.
recordButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (recorder == null) {
recorder = new MediaRecorder();
}
stopped=false;
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile("/sdcard/sample.3gp");
recorder.setMaxDuration(MAX_DURATION);
//Progressbar
pb.setMax(MAX_DURATION);
pb.setProgressTintList(ColorStateList.valueOf(Color.WHITE));
new CountDownTimer(MAX_DURATION, 250) {
public void onTick(long millisUntilFinished) {
pb.setProgress(pb.getProgress() + 250);
}
public void onFinish() {
}
}.start();
All of this is happening within a dialog, so how do I clear the dialog's contents so that the progress bar goes back to its default value.
long timestamp = DateUtils.getCurrentTimeMillis();
String imagePath = Environment.getExternalStorageDirectory() + "/testing/" + timestamp + "_D_FM_" + "John" + ".mp3";
MediaRecorder mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_RECOGNITION); mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mRecorder.setOutputFile(imagePath);
mRecorder.setAudioEncodingBitRate(16);
mRecorder.setAudioSamplingRate(44100);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
// Starting record time
recordTime = 0;
// Show TextView that displays record time
try {
mRecorder.prepare();
mRecorder.start();
// Change isRecroding flag to true
isRecording = true;
handler.post(UpdateRecordTime);
} catch (IOException e) {
FRLog.e("LOG_TAG", "prepare failed", e);
}
When click audio playing:
private MediaPlayer mPlayer;
private void playAudio(final SeekBar audioSeekbar, int position, final ImageButton audioplayImgBtn, String fileName) {
seekBar = audioSeekbar;
if (audio_playing && audio_position == position) {
if (isPaused) {
mPlayer.start();
handler.post(UpdatePlayTime);
audioplayImgBtn.setImageResource(R.drawable.ic_pause);
isPaused = false;
} else {
mPlayer.pause();
audioplayImgBtn.setImageResource(R.drawable.ic_messages_audio_play);
isPaused = true;
}
} else {
if (audio_playing && audio_position != position) {
mPlayer.pause();
audioplayImgBtn.setImageResource(R.drawable.ic_messages_audio_play);
isPaused = true;
}
audio_position = position;
audioSeekbar.setProgress(0);
audioplayImgBtn.setImageResource(R.drawable.ic_pause);
if (mPlayer != null) {
if (mPlayer.isPlaying()) {
mPlayer.stop();
mPlayer.reset();
mPlayer.release();
mPlayer = null;
} else {
mPlayer.reset();
mPlayer.release();
mPlayer = null;
}
}
mPlayer = new MediaPlayer();
playTime = 0;
handler = new Handler();
// Reset max and progress of the SeekBar
try {
// Initialize the player and start playing the audio
mPlayer.setDataSource(Environment.getExternalStorageDirectory() + "/testing/" + fileName);
mPlayer.prepare();
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
audioSeekbar.setMax(mPlayer.getDuration());
mPlayer.start();
audio_playing = true;
handler.post(UpdatePlayTime);
}
});
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
audioplayImgBtn.setImageResource(R.drawable.ic_messages_audio_play);
audioSeekbar.setProgress(0);
audio_playing = false;
handler.removeCallbacksAndMessages(null);
}
});
// Post the play progress
// updated code by manikandan
audioSeekbar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (mPlayer.isPlaying()) {
SeekBar sb = (SeekBar) v;
mPlayer.seekTo(sb.getProgress());
}
return false;
}
});
audioSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean fromUser) {
if (mPlayer != null && fromUser) {
mPlayer.seekTo(seekBar.getProgress());
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (mPlayer != null) {
if (mPlayer.isPlaying()) {
mPlayer.seekTo(seekBar.getProgress());
}
}
}
});
} catch (IOException e) {
FRLog.e("LOG_TAG", "prepare failed", e);
}
}
}
Runnable UpdatePlayTime = new Runnable() {
public void run() {
if (mPlayer != null) {
if (mPlayer.isPlaying()) {
seekBar.setProgress(mPlayer.getCurrentPosition());
handler.postDelayed(this, 500);
}
}
}
};
I'm playing video from web server, the video is playing on videoview nicely, but some samsung mobile playing the video on 90 degree rotation. But the same video playing without ration on others devices.
public void playVideo(String videoPath) {
try {
vidFull.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setOnInfoListener(new MediaPlayer.OnInfoListener() {
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
switch (what) {
case MediaPlayer.MEDIA_INFO_BUFFERING_START:
progressBar.setVisibility(View.VISIBLE);
break;
case MediaPlayer.MEDIA_INFO_BUFFERING_END:
progressBar.setVisibility(View.GONE);
break;
}
return false;
}
});
}
});
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(vidFull);
vidFull.setMediaController(mediaController);
vidFull.setVideoPath(videoPath);
vidFull.requestFocus();
vidFull.start();
videoArrayLength = videoArrayLength -1;
vidpointer = 1;
//Goutam 17.03.2016
vidFull.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
logCollection.setLogERed(""+videoArrayLength);
try {
if (videoArrayLength > 0){
MediaController mediaController = new MediaController(FullPost.this);
mediaController.setAnchorView(vidFull);
vidFull.setMediaController(mediaController);
//vidFull.setVideoPath("http://www.sample-videos.com/video/mp4/480/big_buck_bunny_480p_1mb.mp4");
logCollection.setLogERed(basevideourl+videoArray.optJSONObject(vidpointer).getString("vdLink"));
vidFull.setVideoPath(basevideourl + videoArray.optJSONObject(vidpointer).getString("vdLink"));
vidFull.requestFocus();
vidFull.start();
videoArrayLength = videoArrayLength - 1;
vidpointer = vidpointer + 1;
}else {
logCollection.showToastLong("No more video to play.");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(this, "Error connecting", Toast.LENGTH_SHORT).show();
}
}
Please help, thanks in advance.
I think you telling about orientation change. You can handle this by setting screenOrientation to activity in AndroidManifest.
<activity android:name=".Main2Activity"
android:screenOrientation="portrait">
</activity>
I am plying all sounds from raw folder. Using playSound() and releasing sound after completion as well on error releasing sound. Still i am getting error(-19,0) after couple of sounds played using playSound().
public static MediaPlayer mediaPlayer;
public static boolean playSound(final Context context, int resId) {
if(releaseSound()){
mediaPlayer = MediaPlayer.create(context, resId);
mediaPlayer.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.d("test", "Media player error :" + what + " extra:" + extra);
if(what == 19)
FireToast
.showToast(context,
"MediaPlayer error (Out of buffer). Please restart your application.");
releaseSound();
mp.release();
mp = null;
return false;
}
});
if (resId == 0) {
FireToast.showToast(context, "File not found");
return false;
}
// mediaPlayer = MediaPlayer.create(context, resId);
try {
if (mediaPlayer != null)
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
releaseSound();
FireToast.showToast(context,"MediaPlayer song completed.");
}
});
mediaPlayer.start();
setPause(false);
return true;
} catch (IllegalStateException e) {
e.printStackTrace();
return false;
}
}
return false;
}
public static boolean releaseSound() {
try {
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
}
mediaPlayer = null;
isPause = false;
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
I tried a lot of methods, I made a lot of changes on my code, I read Android MediaPlayer document, I tried StackOverflow examples but none of them could solve my problem.
My problem: When I press the home button of emulator or phone then reopen the app it is starting from the beginning.
Hope you can help me. Thanks in advance.
Here is my code :
public class Mediaplayer extends Activity implements OnCompletionListener,
OnErrorListener, OnInfoListener, OnPreparedListener,
OnSeekCompleteListener, OnVideoSizeChangedListener,
SurfaceHolder.Callback, MediaController.MediaPlayerControl {
Display currentDisplay;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
MediaPlayer mediaPlayer;
MediaController controller;
int videoWidth = 0;
int videoHeight = 0;
boolean readyToPlay = false;
public final static String LOGTAG = "CUSTOM_VIDEO_PLAYER";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.video);
surfaceView = (SurfaceView) this.findViewById(R.id.SurfaceView);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnInfoListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnVideoSizeChangedListener(this);
mediaPlayer.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
String filePath = "http://cdn.example.com/wp-content/uploads/Almost.Human-S01E10.mp4";
try {
mediaPlayer.setDataSource(filePath);
} catch (IllegalArgumentException e) {
Log.v(LOGTAG, e.getMessage());
finish();
} catch (IllegalStateException e) {
Log.v(LOGTAG, e.getMessage());
finish();
} catch (IOException e) {
Log.v(LOGTAG, e.getMessage());
finish();
}
controller = new MediaController(this);
currentDisplay = getWindowManager().getDefaultDisplay();
}
public void surfaceCreated(SurfaceHolder holder) {
// Log.v(LOGTAG, "surfaceCreated Called");
mediaPlayer.setDisplay(holder);
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// Log.v(LOGTAG, e.getMessage());
finish();
} catch (IOException e) {
// Log.v(LOGTAG, e.getMessage());
finish();
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Log.v(LOGTAG, "surfaceChanged Called");
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.v(LOGTAG, "surfaceDestroyed Called");
}
public void onCompletion(MediaPlayer mp) {
Log.v(LOGTAG, "onCompletion Called");
finish();
}
public boolean onError(MediaPlayer mp, int whatError, int extra) {
Log.v(LOGTAG, "onError Called");
if (whatError == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
Log.v(LOGTAG, "Media Error, Server Died " + extra);
} else if (whatError == MediaPlayer.MEDIA_ERROR_UNKNOWN) {
Log.v(LOGTAG, "Media Error, Error Unknown " + extra);
}
return false;
}
public boolean onInfo(MediaPlayer mp, int whatInfo, int extra) {
if (whatInfo == MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING) {
Log.v(LOGTAG, "Media Info, Media Info Bad Interleaving " + extra);
} else if (whatInfo == MediaPlayer.MEDIA_INFO_NOT_SEEKABLE) {
Log.v(LOGTAG, "Media Info, Media Info Not Seekable " + extra);
} else if (whatInfo == MediaPlayer.MEDIA_INFO_UNKNOWN) {
Log.v(LOGTAG, "Media Info, Media Info Unknown " + extra);
} else if (whatInfo == MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING) {
Log.v(LOGTAG, "MediaInfo, Media Info Video Track Lagging " + extra);
/*
* Android Version 2.0 and Higher } else if (whatInfo ==
* MediaPlayer.MEDIA_INFO_METADATA_UPDATE) {
* Log.v(LOGTAG,"MediaInfo, Media Info Metadata Update " + extra);
*/
}
return false;
}
public void onPrepared(MediaPlayer mp) {
Log.v(LOGTAG, "onPrepared Called");
videoWidth = mp.getVideoWidth();
videoHeight = mp.getVideoHeight();
if (videoWidth > currentDisplay.getWidth()
|| videoHeight > currentDisplay.getHeight()) {
float heightRatio = (float) videoHeight
/ (float) currentDisplay.getHeight();
float widthRatio = (float) videoWidth
/ (float) currentDisplay.getWidth();
if (heightRatio > 1 || widthRatio > 1) {
if (heightRatio > widthRatio) {
videoHeight = (int) Math.ceil((float) videoHeight
/ (float) heightRatio);
videoWidth = (int) Math.ceil((float) videoWidth
/ (float) heightRatio);
} else {
videoHeight = (int) Math.ceil((float) videoHeight
/ (float) widthRatio);
videoWidth = (int) Math.ceil((float) videoWidth
/ (float) widthRatio);
}
}
}
surfaceView.setLayoutParams(new LinearLayout.LayoutParams(videoWidth,
videoHeight));
mp.start();
controller.setMediaPlayer(this);
controller.setAnchorView(this.findViewById(R.id.MainView));
controller.setEnabled(true);
controller.show();
}
#Override
protected void onPause() {
super.onPause();
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
} else {
return;
}
}
public void onSeekComplete(MediaPlayer mp) {
Log.v(LOGTAG, "onSeekComplete Called");
}
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
Log.v(LOGTAG, "onVideoSizeChanged Called");
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
public int getBufferPercentage() {
return 0;
}
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
public void pause() {
mediaPlayer.pause();
}
public void seekTo(int pos) {
mediaPlayer.seekTo(pos);
}
public void start() {
mediaPlayer.start();
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
controller.show();
return false;
}
#Override
public int getAudioSessionId() {
// TODO Auto-generated method stub
return 0;
}
}
I understand you have accepted an answer but I'll explain what the problem was based on your comments on your question and the comments from you and Nana on Nana's answer.
A SurfaceView is destroyed when it is no longer visible and recreated when it becomes visible again.
You are calling mp.pause() in your Activity onPause() method.
When you go to the 'recent' apps list and attempt to restart the app, the SurfaceView is recreated.
In surfaceCreated method you are calling mp.prepare() but at this point mp is in a paused state and calling prepare() on a paused Mediaplayer will throw an IllegalStateException.
You have a try / catch block which catches IllegalStateException and calls finish() - this is why the first attempt to restart the app from the 'recent' list causes the the Activity to be destroyed.
As a result of the above sequence of events you need a second attempt to re-open the app from the 'recent' list but as the Activity has been destroyed it will go through a full creation (with onCreate(..) being called. This is why it starts from the beginning.
The answer from Nana is a workaround but it will still mean having to use two attempts to restart your Activity from the 'recent' list.
Unfortunately the MediaPlayer class is lacking in methods for checking the 'state' with isPlaying being the only useful method for any state. It's a shame the class devs didn't think to add a getState() method (or similar) to allow checking for whether it's started, playing, stopped, paused etc.
One way of preventing the IllegalStateException would be to have a boolean called isPaused (for example) then modify your Activity onPause() as follows...
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
isPaused = true;
}
...and in surfaceCreated(...)...
try {
if (isPaused) {
mpStart();
isPaused = false;
}
else
mediaPlayer.prepare();
}
// catch blocks here
The activity is being restarted thereby triggering surfaceCreated() and mediaPlayer.prepare(), which in turns calls onPrepared and mp.start() to restart the track. You have no mechanism to resume playing. Do this - Get the last position of the track when paused(HOME button is pressed), then when the activity is "recreated" resume playing the track by seeking to that last position. Modify your onPause() and onPrepared() as follows:
int length = 0;
//save last position when activity is paused
#Override
protected void onPause() {
super.onPause();
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
length = mediaPlayer.getCurrentPosition();
} else {
return;
}
}
public void onPrepared(MediaPlayer mp) {
........
.........
.........
mp.start();
//seek to saved position.
mp.seekTo(length);
}