The surface has been releasedException android - android

I have created media player run time I have change url but surface view is black and expected url is not playing i got some error in my logcat i have posted my error and media player code. why it's happening?
code :
public class MediaPlayerActivity extends Activity implements
SurfaceHolder.Callback, OnCompletionListener, OnClickListener {
/**
* MediaPlayer Field
*/
private MediaPlayer mediaPlayer;
/**
* surfaceHolder Field
*/
private SurfaceHolder surfaceHolder;
/**
* playerSurfaceView Field
*/
private SurfaceView playerSurfaceView;
/**
* wifiUSerName Field
*/
private static String wifiUSerName = "RMS";
/**
* List of Url Field
*/
private static List<Playfile> urls;
/**
* Button previous
*/
private Button prevButton;
/**
* Button play And Pause
*/
private Button playAndPauseButton;
/**
* Button Next
*/
private Button nextButton;
/**
* seekbar Field
*/
private SeekBar seekbar;
/**
* currentIndex Field
*/
private int currentIndex = 0;
/**
* PlayMode boolean
*/
private boolean isPlayMode = false;
/**
* FooterLayoutShow boolean
*/
private boolean isFooterLayoutShow = false;
/**
* progressDialog Field
*/
private ProgressDialog progressDialog;
/**
* Runnable Field to run on Every Second
*/
private Runnable onEverySecond = null;
/**
* FrameLayout Field
*/
private FrameLayout rootFrameLayout;
/**
* RelativeLayout footerButton
*/
private RelativeLayout footerButtonLayout;
// private ProgressBar progBar;
/**
* Method is called at very first time. set ui.
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_player);
initViewControls();
getDataFromBundle();
/*
* if (MainActivity.progress.isShowing()) {
* MainActivity.progress.dismiss(); }
*/
mediaPlayer = new MediaPlayer();
}
/**
* Method is used to initialize media player object and flag, set default
* text on button.
*/
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
mediaPlayer = new MediaPlayer();
isPlayMode = true;
playAndPauseButton.setBackgroundResource(R.drawable.pause);
// Reset Urls
urls = MasterData.getValueBasedOnKey(wifiUSerName);
}
/**
* Method is used to get data from bundle.
*/
private void getDataFromBundle() {
if (getIntent().getExtras() != null) {
Bundle bundle = getIntent().getExtras();
wifiUSerName = bundle.getString("wifiusername");
urls = MasterData.getValueBasedOnKey(wifiUSerName);
} else {
showToast("No data available");
// Take the user to home
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(homeIntent);
}
}
/**
* Method is used to initialise view controls.
*/
private void initViewControls() {
playerSurfaceView = (SurfaceView) findViewById(R.id.playersurface);
prevButton = (Button) findViewById(R.id.activity_mediaplayer_prev_btn);
playAndPauseButton = (Button) findViewById(R.id.activity_mediaplayer_play_and_pause_btn);
nextButton = (Button) findViewById(R.id.activity_mediaplayer_next_btn);
seekbar = (SeekBar) findViewById(R.id.activity_mediaplayer_seekbar);
rootFrameLayout = (FrameLayout) findViewById(R.id.activity_media_player_root_layout);
footerButtonLayout = (RelativeLayout) findViewById(R.id.activity_mediaplayer_footer_button_layout);
footerButtonLayout.setVisibility(View.GONE);
prevButton.setOnClickListener(this);
playAndPauseButton.setOnClickListener(this);
nextButton.setOnClickListener(this);
surfaceHolder = playerSurfaceView.getHolder();
surfaceHolder.addCallback(this);
seekbar.setVisibility(View.INVISIBLE);
rootFrameLayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
seekbar.setVisibility(View.INVISIBLE);
if (!isFooterLayoutShow) {
isFooterLayoutShow = true;
footerButtonLayout.setVisibility(View.VISIBLE);
} else {
isFooterLayoutShow = false;
footerButtonLayout.setVisibility(View.INVISIBLE);
}
} else {
seekbar.setVisibility(View.VISIBLE);
}
return true;
}
});
//
// showProgressDialog();
}
/**
* Surface Holder Callback Methods
*/
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
try {
playMediaPlayer();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
Utils.writeToSDCard("Exception -" + e.getMessage());
} catch (SecurityException e) {
// TODO Auto-generated catch block
Utils.writeToSDCard("Exception -" + e.getMessage());
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
Utils.writeToSDCard("Exception -" + e.getMessage());
}
}
/**
* Method is used to play media file.
*/
private void playMediaPlayer() {
if (urls != null) {
try {
if (currentIndex < urls.size()) {
//
// showProgressDialog();
if (mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
}
mediaPlayer.reset();
mediaPlayer.setDisplay(surfaceHolder);
/*
* System.out.println(" url :: " +
* urls.get(currentIndex).getUrl());
*/
boolean a=MasterData.songtest;
/*if(MasterData.songtest){
mediaPlayer.setDataSource("http://122.165.94.246/rms/trans.mp4");
}else{*/
Log.e("print","for url :"+MasterData.songtest+urls.get(currentIndex).getUrl());
mediaPlayer.setDataSource(urls.get(currentIndex).getUrl());
/*}*/
showToast("Preparing media player");
//mediaPlayer.prepareAsync();
mediaPlayer.prepare();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer
.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
#Override
public void onBufferingUpdate(MediaPlayer mp,
int percent) {
// TODO Auto-generated method stub
//
// if(percent == 100){
// stopProgressDialog();
// }else {
// showProgressDialog();
// }
}
});
// ****************************************
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
/*
* if (progressDialog != null &&
* progressDialog.isShowing()) {
* progressDialog.dismiss(); }
*/
seekbar.setMax(mediaPlayer.getDuration());
seekbar.postDelayed(onEverySecond, 1000);
mediaPlayer.start();
// stopProgressDialog();
}
});
onEverySecond = new Runnable() {
#Override
public void run() {
if (seekbar != null && mediaPlayer != null) {
seekbar.setProgress(mediaPlayer
.getCurrentPosition());
}
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
seekbar.postDelayed(onEverySecond, 1000);
}
}
};
seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar,
int progress, boolean fromUser) {
if (fromUser) {
// this is when actually seekbar has been seeked
// to a new position
mediaPlayer.seekTo(progress);
}
}
});
// ***************************************
} /*
* else { mediaPlayer.stop(); mediaPlayer.reset();
* playAndPauseButton.setBackgroundResource(R.drawable.stop); }
*/
} catch (IllegalStateException e) {
} catch (Exception e) {
Utils.writeToSDCard("Exception -" + e.getMessage());
// showToast("Some error occured!");
// stopProgressDialog();
}
} else {
showToast("No urls list present.Download xml file");
// stopProgressDialog();
// finish();
startActivity(new Intent(this, MainActivity.class));
}
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.reset();
}
}
/**
* Listner for Media File on Completion
*/
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
currentIndex++;
progressDialog = null;
playMediaPlayer();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}
}
/*#Override
protected void onPause() {
super.onPause();
}*/
/**
* Method is used to controls all click event on view portion.
*/
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.activity_mediaplayer_next_btn:
progressDialog = null;
if (mediaPlayer != null) {
playNextVideo();
}
break;
case R.id.activity_mediaplayer_prev_btn:
progressDialog = null;
if (mediaPlayer != null) {
playPrevVideo();
}
break;
case R.id.activity_mediaplayer_play_and_pause_btn:
playAndPauseVideo();
break;
default:
break;
}
}
/**
* Method is used to play and pause media player based on click event.
*/
private void playAndPauseVideo() {
if (isPlayMode) {
isPlayMode = false;
playAndPauseButton.setBackgroundResource(R.drawable.play);
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
} else {
isPlayMode = true;
playAndPauseButton.setBackgroundResource(R.drawable.pause);
if (mediaPlayer != null) {
mediaPlayer.start();
}
}
}
/**
* Method is used to play previous video.
*/
private void playPrevVideo() {
if (currentIndex > 0) {
//
// showProgressDialog();
currentIndex--;
playMediaPlayer();
} else {
showToast("No Prev Video Present.");
}
}
/**
* Method is used to play next video.
*/
private void playNextVideo() {
if (currentIndex < urls.size() - 1) {
//
// showProgressDialog();
currentIndex++;
playMediaPlayer();
} else {
showToast("No Next Video Present.");
}
}
/**
* Method is used to show toast based on message param.
*
* #param message
*/
private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
/**
* Method is used to show progress dialog.
*/
private void showProgressDialog() {
if (progressDialog == null) {
progressDialog = ProgressDialog.show(this, "", "Buffering...");
}
}
/**
* Method is used to stop progress dialog.
*/
private void stopProgressDialog() {
if (progressDialog != null) {
progressDialog.dismiss();
progressDialog = null;
}
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer = null;
}
}
}

Related

Unable to call a method on onStopTrackingTouch(SeekBar seekBar)

In my application I can successfully call a method flash_toggle_times(progress); when toggle Button is pressed. But when I am calling same method in public void onStopTrackingTouch(SeekBar seekBar) It is not being called. Do not know why?
Here is complete code
public class MainActivity extends ActionBarActivity implements OnSeekBarChangeListener {
SeekBar seekBar;
TextView textView;
ToggleButton toggleButton;
boolean positionON = false;
private Camera mCamera;
private Camera.Parameters mParams;
boolean lightON = false;
boolean changeIntensity = false;
int progress = 0;
private String TAG = "SeekBar LOG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeVariables();
textView.setText("Covered : " + seekBar.getProgress() + "/" + seekBar.getMax());
seekBar.setOnSeekBarChangeListener(this);
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// positionON = (isChecked) ? true : false;
positionON = isChecked;
if (isChecked) {
//Here flash_toggle_times(progress) is being called successfully
// flash_toggle_times(progress);
} else {
}
}
});
}
private void initializeVariables() {
seekBar = (SeekBar) findViewById(R.id.m_seekbar);
textView = (TextView) findViewById(R.id.m_tv);
toggleButton = (ToggleButton) findViewById(R.id.m_toggle_button);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
textView.setText("Covered On Stop: " + progress + "/" + seekBar.getMax() + "\n" + changeIntensity);
// If button is On, Turn on Light
Toast.makeText(getApplicationContext(), "StopTrackingTouch: " + progress, Toast.LENGTH_SHORT).show();
if(progress > 0){
//Here when this method is not being called.
flash_toggle_times(progress);
Toast.makeText(getApplicationContext(), "Calling in if", Toast.LENGTH_SHORT).show();
}
Log.d(TAG, "StopTrackingTouch");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
Log.d(TAG , "StartTrackingTouch()");
}
#Override
public void onProgressChanged(SeekBar seekBar, int progressValue, boolean fromUser) {
progress = progressValue;
// Toast.makeText(getApplicationContext(), "ProgressChanged : " + progress, Toast.LENGTH_SHORT).show();
Log.d(TAG,"ProgressChanged");
}
public void flash_toggle_times(final int delay) {
mCamera = Camera.open();
final Parameters p = mCamera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
Thread t = new Thread() {
public void run() {
try {
// Switch on the cam for app's life
if (mCamera == null) {
// Turn on Cam
mCamera = Camera.open();
try {
mCamera.setPreviewDisplay(null);
} catch (IOException e) {
e.printStackTrace();
}
mCamera.startPreview();
}
final int[] counter = {delay};
while(positionON )
{
if(counter[0] > 0){
toggleFlashLight();
sleep(counter[0]*100);
}
}
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
} catch (Exception e){
e.printStackTrace();
}
}
};
t.start();
}
public void turnOn(){
if (mCamera != null) {
// Turn on LED
mParams = mCamera.getParameters();
mParams.setFlashMode(Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(mParams);
}
lightON = true;
}
public void turnOff(){
// Turn off flashlight
if (mCamera != null) {
mParams = mCamera.getParameters();
if (mParams.getFlashMode().equals(Parameters.FLASH_MODE_TORCH)) {
mParams.setFlashMode(Parameters.FLASH_MODE_OFF);
mCamera.setParameters(mParams);
}
}
lightON = false;
}
private void toggleFlashLight() {
if (!lightON) {
turnOn();
} else {
turnOff();
}
}
}

How can i exit my app with out this error

I created a Karaoke application. But I can't stop the MediaPlayer with out an error. When I press Back Button to go to home, I get "sorry ,Application has stopped working" The same thing happens if I try to start another activity
public class Main extends Activity implements MediaPlayerControl {
private MediaController mMediaController;
private MediaPlayer mMediaPlayer;
Handler mHandler = new Handler();
public TextView subtitles,subtitles2;
static Context context;
#SuppressLint("HandlerLeak")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.Main);
subtitles = (TextView) findViewById(R.id.subs2);
subtitles2 = (TextView) findViewById(R.id.subs21);
mMediaPlayer = new MediaPlayer();
mMediaController = new MediaController(this)
/*
* {
*
* #Override public void hide() { mMediaController.show(0); } }
*/;
mMediaController.setMediaPlayer(Main.this);
mMediaController.setAnchorView(findViewById(R.id.AudioView));
mMediaController.setPrevNextListeners(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Next button clicked
Intent intent = new Intent(Main.this, Hello.class);
startActivity(intent);
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
// Previous button clicked
Intent intent = new Intent(Main.this, Sorry.class);
startActivity(intent);
}
});
// String audioFile = "" ;
try {
mMediaPlayer.setDataSource(this, Uri
.parse("android.resource://com.app.suadmon/raw/buchatri"));
mMediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
final long currentPos = mMediaPlayer.getCurrentPosition();
if (currentPos < 5130) {
subtitles.setText("1111+");
} else if (currentPos > 5130 && currentPos < 10572) {
subtitles.setText("555+");
} else if (currentPos > 10572 && currentPos < 10597) {
subtitles.setText("666+");
} else if (currentPos > 15312 && currentPos < 18478) {
subtitles.setText("777+");
} else if (currentPos > 18478 && currentPos < 24191) {
subtitles.setText("888+");
} else if (currentPos > 24191 && currentPos < 28137) {
subtitles.setText("999+");
} else if (currentPos > 28137 && currentPos < 29500) {
subtitles.setText("Thank you");
subtitles2.setText(".............");
}
mHandler.sendEmptyMessageDelayed(0, 1);
}
};
mHandler.sendEmptyMessage(0);
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mHandler.post(new Runnable() {
public void run() {
mMediaController.show(0);
// mMediaPlayer.reset();
mMediaPlayer.start();
}
});
}
});
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
Intent stopplay = new Intent(Main.this, Hello.class);
startActivity(stopplay);
}
});
}
protected void onDestroy() {
super.onDestroy();
mMediaPlayer.stop();
mMediaPlayer.release();
}
public void releaseMediaPlayer(){
if(mMediaPlayer != null){
mMediaPlayer.release();
mMediaPlayer = null;
}
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
public int getBufferPercentage() {
int percentage = (mMediaPlayer.getCurrentPosition() * 100)
/ mMediaPlayer.getDuration();
return percentage;
}
public int getCurrentPosition() {
return mMediaPlayer.getCurrentPosition();
}
public int getDuration() {
return mMediaPlayer.getDuration();
}
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
public void seekTo(int pos) {
mMediaPlayer.seekTo(pos);
}
#Override
public void pause() {
// TODO Auto-generated method stub
mMediaPlayer.pause();
}
protected void onPause() {
super.onPause();
mMediaPlayer.getCurrentPosition();
mMediaPlayer.pause();
}
protected void onResume() {
super.onResume();
mMediaPlayer.seekTo(0);
mMediaPlayer.start();
}
// public void onUserLeaveHint(){
// mMediaPlayer.stop();
// super.onUserLeaveHint();
// }
/*
* public void stopPlayback(){ mMediaPlayer.stop(); }
*/
public void start() {
mMediaPlayer.start();
}
public boolean onTouchEvent(MotionEvent event) {
mMediaController.show(0);
return false;
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
finish();
Intent intent = new Intent(Main.this, Show.class);
startActivity(intent);
super.onBackPressed();
}
}
and Log Cat's here.
How can I fix this. I have no idea.
Can anyone help me. Please !!!
You need to stop and release the media player before your activity finishes. Try adding this to your activity:
#Override
protected void onDestroy() {
super.onDestroy();
if(mMediaPlayer != null)
{
mMediaPlayer.stop();
mMediaPlayer.release();
}
}

How can I stop MediaPlayer without error when I press Back or go to another activity

I created a Karaoke application. But I can't stop the MediaPlayer with out an error. When I press Back Button to go to home, I get "sorry ,Application has stopped working" The same thing happens if I try to start another activity.
This my code.
public class Main extends Activity implements MediaPlayerControl, OnClickListener {
private MediaController mMediaController;
private MediaPlayer mMediaPlayer;
public TextView subtitles;
Handler mHandler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
subtitles = (TextView) findViewById(R.id.subs1);
Button btnvol = (Button) findViewById(R.id.volc);
btnvol.setOnClickListener(this);
mMediaPlayer = new MediaPlayer();
mMediaController = new MediaController(this);
mMediaController.setMediaPlayer(Main.this);
mMediaController.setAnchorView(findViewById(R.id.audioView));
try {
mMediaPlayer
.setDataSource(
this,
Uri.parse("android.resource://com.app.audioplayer/raw/buchatri"));
mMediaPlayer.prepare();
} catch (IllegalStateException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
final long currentPos = mMediaPlayer.getCurrentPosition();
if (currentPos < 5130) {
subtitles.setText("Stupid");
} else if (currentPos > 5130 && currentPos < 10572) {
subtitles.setText("Sorry");
} else if (currentPos > 10572 && currentPos < 10597) {
subtitles.setText("555+");
} else if (currentPos > 15312 && currentPos < 18478) {
subtitles.setText("OMG");
} else if (currentPos > 18478 && currentPos < 24191) {
subtitles.setText("AFK");
} else if (currentPos > 24191 && currentPos < 28137) {
subtitles.setText("Help me !");
} else if (currentPos > 28137 && currentPos < 29500) {
subtitles.setText("Oh no !");
}
mHandler.sendEmptyMessageDelayed(0, 1);
}
};
mHandler.sendEmptyMessage(0);
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mHandler.post(new Runnable() {
public void run() {
mMediaController.show(0);
mMediaPlayer.start();
}
});
}
});
}
protected void onDestroy() {
super.onDestroy();
mMediaPlayer.stop();
mMediaPlayer.release();
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
public int getBufferPercentage() {
int percentage = (mMediaPlayer.getCurrentPosition() * 100)
/ mMediaPlayer.getDuration();
return percentage;
}
public int getCurrentPosition() {
return mMediaPlayer.getCurrentPosition();
}
public int getDuration() {
return mMediaPlayer.getDuration();
}
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
#Override
public void pause() {
// TODO Auto-generated method stub
super.onPause();
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
public void seekTo(int pos) {
mMediaPlayer.seekTo(pos);
}
public void start() {
mMediaPlayer.start();
}
public boolean onTouchEvent(MotionEvent event) {
mMediaController.show(0);
return false;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
I think I have an error with "if else". How can I fix this ?
Try first mMediaPlayer.stop() and then release it by mMediaPlayer.release()
you can try this,
after release you should set mediaplayer null
private void releaseMediaPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}

prepareAsync of MediaPlayer in one Activity, play in another

I am developing an application that, among other things, plays some video files (streaming). I would like to prepare the MediaPlayer in one activity but play the video once it is ready in another activity, so that the user can navigate through the content of the first activity to kill some time. Is this possible?
There is an static MediaPlayer defined in the Application class, like this:
public class EGDF_App extends Application {
private static MediaPlayer mediaPlayer = null;
public static MediaPlayer getMediaPlayer() {
if(mediaPlayer == null)
return new MediaPlayer();
else
return mediaPlayer;
}
}
I have a button with a text (Load video). This text is changed when the video is ready, and when the user clicks on it, it triggers the following activity.
The problem is that I get the following error in LogCat:
09-06 20:43:34.606: D/ChapterPlayer(31999): surfaceCreated called
09-06 20:43:34.684: V/ChapterPlayer(31999): startVideoPlayback
09-06 20:43:34.684: E/MediaPlayer(31999): start called in state 1
09-06 20:43:34.684: E/MediaPlayer(31999): error (-38, 0)
09-06 20:43:34.684: D/ChapterPlayer(31999): surfaceChanged called
09-06 20:43:34.700: E/MediaPlayer(31999): Attempt to call getDuration without a valid mediaplayer
09-06 20:43:34.715: E/MediaPlayer(31999): Error (-38,0)
09-06 20:43:34.715: D/ChapterPlayer(31999): onCompletion called
09-06 20:43:34.751: E/MediaPlayer(31999): Attempt to call getDuration without a valid mediaplayer
This is the code contained in the first Activity:
public void watchChapter(View view){
Log.i("Button", "Watch chapter button PRESSED");
Button b = (Button) view;
String loadChapter = getString(R.string.load_chapter_button_text);
String watchChapter = getString(R.string.watch_chapter_button_text);
if(((String) b.getText()).equals(loadChapter)){
prepareVideo(view);
}else if(((String) b.getText()).equals(watchChapter)){
Intent intent = new Intent(this,ChapterAsyncMediaPlayerActivity.class);
intent.putExtra(Constants.chapterVideoResParse, getIntent().getExtras().getString(Constants.chapterVideoResParse));
intent.putExtra("duration", String.valueOf(duration));
startActivity(intent);
}
}
private void prepareVideo(View view){
MediaPlayer mMediaPlayer;
String path;
final Button button = (Button) view;
String resource = extras.getString(Constants.chapterVideoResParse);
path = SecurityHandler.obtainURL(resource, this.getResources().openRawResource(R.raw.output), 10);
try {
// Gets the media player and set the listeners
mMediaPlayer = EGDF_App.getMediaPlayer();
mMediaPlayer.setDataSource(path);
mMediaPlayer.prepareAsync();
mMediaPlayer.setOnPreparedListener(new OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp) {
button.setText(getString(R.string.watch_chapter_button_text));
Log.i("MediaPlayer", "MediaPlayer ready");
duration = mp.getDuration();
Log.i("Video duration", String.valueOf(mp.getDuration()));
}
});
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And this is the code in the second Activity:
public class ChapterAsyncMediaPlayerActivity extends Activity implements
OnBufferingUpdateListener, OnCompletionListener,
OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback, MediaPlayerControl {
private static final String TAG = "ChapterPlayer";
private int mVideoWidth;
private int mVideoHeight;
private MediaPlayer mMediaPlayer;
private MediaController mController;
private SurfaceView mPreview;
private SurfaceHolder holder;
// private String path;
// private boolean mIsVideoSizeKnown = false;
private boolean mIsVideoReadyToBePlayed = false;
private Handler handler = new Handler();
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chapter_media_player);
mPreview = (SurfaceView) findViewById(R.id.mediaPlayerSurface);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setKeepScreenOn(true);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mController.show();
return false;
}
private void playVideo() {
doCleanUp();
try {
// Create a new media player and set the listeners
mMediaPlayer = EGDF_App.getMediaPlayer();
// mMediaPlayer.setDataSource(path);
mMediaPlayer.setDisplay(holder);
// mMediaPlayer.prepareAsync();
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mController = new MediaController(this);
} catch (Exception e) {
Log.e(TAG, "error: " + e.getMessage(), e);
}
}
public void onPrepared(MediaPlayer mediaplayer) {
Log.d(TAG, "onPrepared called");
mIsVideoReadyToBePlayed = true;
mController.setMediaPlayer(this);
mController.setAnchorView(findViewById(R.id.mediaPlayerSurface));
handler.post(new Runnable(){
#Override
public void run() {
mController.setEnabled(true);
mController.show();
}
});
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) {
Log.d(TAG, "surfaceChanged called");
}
public void surfaceDestroyed(SurfaceHolder surfaceholder) {
Log.d(TAG, "surfaceDestroyed called");
}
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated called");
playVideo();
mIsVideoReadyToBePlayed = true;
mController.setMediaPlayer(this);
mController.setAnchorView(findViewById(R.id.mediaPlayerSurface));
handler.post(new Runnable(){
#Override
public void run() {
mController.setEnabled(true);
mController.show();
}
});
if (mIsVideoReadyToBePlayed) {
startVideoPlayback();
}
}
#Override
protected void onPause() {
super.onPause();
mMediaPlayer.pause();
}
#Override
protected void onRestart() {
super.onPause();
mMediaPlayer.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
doCleanUp();
}
private void releaseMediaPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
private void doCleanUp() {
mVideoWidth = 0;
mVideoHeight = 0;
mIsVideoReadyToBePlayed = false;
}
private void startVideoPlayback() {
Log.v(TAG, "startVideoPlayback");
holder.setFixedSize(mVideoWidth, mVideoHeight);
mMediaPlayer.start();
mMediaPlayer.setScreenOnWhilePlaying(true);
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public int getCurrentPosition() {
if(mMediaPlayer != null)
return mMediaPlayer.getCurrentPosition();
else
return 0;
}
#Override
public int getDuration() {
if(mMediaPlayer != null)
return mMediaPlayer.getDuration();
else
return 0;
}
#Override
public boolean isPlaying() {
if(mMediaPlayer != null)
return mMediaPlayer.isPlaying();
else
return false;
}
#Override
public void pause() {
if(mMediaPlayer != null)
mMediaPlayer.pause();
}
#Override
public void seekTo(int pos) {
mMediaPlayer.seekTo(pos);
}
#Override
public void start() {
if(mMediaPlayer != null)
mMediaPlayer.start();
}
public void onBufferingUpdate(MediaPlayer arg0, int percent) {
Log.d(TAG, "onBufferingUpdate percent:" + percent);
}
public void onCompletion(MediaPlayer arg0) {
Log.d(TAG, "onCompletion called");
}
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
Log.v(TAG, "onVideoSizeChanged called");
if (width == 0 || height == 0) {
Log.e(TAG, "invalid video width(" + width + ") or height(" + height + ")");
return;
}
mVideoWidth = width;
mVideoHeight = height;
if (mIsVideoReadyToBePlayed) {
startVideoPlayback();
}
}
}
I would appreciate some help or advice. Thanks!
I don't think you're saving the MediaPlayer in your application, you're just returning a new instance of it. Try changing it as so:
public static MediaPlayer getMediaPlayer() {
if(mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
}
return mediaPlayer;
}

setLooping don't work in my videoplayer

I am a Android newbie. I want to design my personal videoplayer to play streaming music, so I use MediaPlayer and SurfaceView. The project plays streaming video successfully, but it can't be setloop. I have google many articles and read Android Developer. I can't figure out why mediaPlayer.setLooping(true) don't work here. Thanks^^
mediaPlayer.reset();
mediaPlayer.setDataSource(videoUrl);
mediaPlayer.setLooping(true);
mediaPlayer.prepare();
The code includes two parts: 1.Test_Videoplayer.java 2.Player.java
1.Test_Videoplayer.java
public class Test_Videoplayer extends Activity {
private SurfaceView surfaceView;
private Button btnPause, btnPlayUrl, btnStop;
private SeekBar skbProgress;
private Player player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
surfaceView = (SurfaceView) this.findViewById(R.id.surfaceView1);
btnPlayUrl = (Button) this.findViewById(R.id.btnPlayUrl);
btnPlayUrl.setOnClickListener(new ClickEvent());
btnPause = (Button) this.findViewById(R.id.btnPause);
btnPause.setOnClickListener(new ClickEvent());
btnStop = (Button) this.findViewById(R.id.btnStop);
btnStop.setOnClickListener(new ClickEvent());
skbProgress = (SeekBar) this.findViewById(R.id.skbProgress);
skbProgress.setOnSeekBarChangeListener(new SeekBarChangeEvent());
player = new Player(surfaceView, skbProgress);
}
class ClickEvent implements OnClickListener {
#Override
public void onClick(View arg0) {
if (arg0 == btnPause) {
player.pause();
} else if (arg0 == btnPlayUrl) {
String url = "http://sites.google.com/site/ronforwork/Home/android-2/littleMonster.3gp";
player.playUrl(url);
} else if (arg0 == btnStop) {
player.stop();
}
}
}
class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener {
int progress;
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
this.progress = progress * player.mediaPlayer.getDuration()
/ seekBar.getMax();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
player.mediaPlayer.seekTo(progress);
}
}
}
2.Player.java <-- here is mediaPlayer.setLooping(true)
public class Player implements OnBufferingUpdateListener, OnCompletionListener,
MediaPlayer.OnPreparedListener, SurfaceHolder.Callback {
private int videoWidth;
private int videoHeight;
public MediaPlayer mediaPlayer;
private SurfaceHolder surfaceHolder;
private SeekBar skbProgress;
private Timer mTimer = new Timer();
public Player(SurfaceView surfaceView, SeekBar skbProgress) {
this.skbProgress = skbProgress;
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mTimer.schedule(mTimerTask, 0, 1000);
}
TimerTask mTimerTask = new TimerTask() {
#Override
public void run() {
if (mediaPlayer == null)
return;
if (mediaPlayer.isPlaying() && skbProgress.isPressed() == false) {
handleProgress.sendEmptyMessage(0);
}
}
};
Handler handleProgress = new Handler() {
public void handleMessage(Message msg) {
int position = mediaPlayer.getCurrentPosition();
int duration = mediaPlayer.getDuration();
if (duration > 0) {
long pos = skbProgress.getMax() * position / duration;
skbProgress.setProgress((int) pos);
}
};
};
public void play() {
mediaPlayer.start();
}
public void playUrl(String videoUrl) {
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(videoUrl);
mediaPlayer.setLooping(true);
mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void pause() {
mediaPlayer.pause();
}
public void stop() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
Log.e("mediaPlayer", "surface changed");
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDisplay(surfaceHolder);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnPreparedListener(this);
} catch (Exception e) {
Log.e("mediaPlayer", "error", e);
}
Log.e("mediaPlayer", "surface created");
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
Log.e("mediaPlayer", "surface destroyed");
}
#Override
public void onPrepared(MediaPlayer arg0) {
videoWidth = mediaPlayer.getVideoWidth();
videoHeight = mediaPlayer.getVideoHeight();
if (videoHeight != 0 && videoWidth != 0) {
arg0.start();
}
Log.e("mediaPlayer", "onPrepared");
}
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
}
#Override
public void onBufferingUpdate(MediaPlayer arg0, int bufferingProgress) {
skbProgress.setSecondaryProgress(bufferingProgress);
int currentProgress = skbProgress.getMax()
* mediaPlayer.getCurrentPosition() / mediaPlayer.getDuration();
Log.e(currentProgress + "% play", bufferingProgress + "% buffer");
}
}

Categories

Resources