android - videoView does AsyncTask only once / onPostExecute never gets called - android

I have 3 videos. depending on the videoLong I play the selected video with videoView.
I have 2 questions:
The first time a video is played it works. The video stops at the correct time and finish() is used. BUT any time after that doInBackground doesnt check the other if statements.
My onPostExecute never gets called.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (videoLong == 0) {
videoView
.setVideoURI(Uri
.parse("http://pv...70ab1aae7633.mp4"));
videoView.seekTo(60000 * 10);// 10 mins
videoView.start();
new myAsync().execute();
} else if (videoLong == 1) {
videoView
.setVideoURI(Uri
.parse("http://pv....mp4"));
videoView.seekTo(60000 * 10);// 10 mins
videoView.start();
new myAsync().execute();
} else if (videoLong == 2) {
videoView
.setVideoURI(Uri
.parse("http://pv....mp4"));
videoView.seekTo(60000 * 10);// 10 mins
new myAsync().execute();
videoView.start();
}
}
private class myAsync extends AsyncTask<Void, Integer, Void> {
int duration = 0;
int current = 0;
protected void onPreExecute() {
super.onPreExecute();
System.out.println("on pre execute");
// alertDialog = new AlertDialog.Builder(PlayVideoActivity.this);
}
#Override
protected Void doInBackground(Void... params) {
videoView
.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
duration = videoView.getDuration();
}
});
videoView
.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// Do whatever u need to do here
System.out.println("video complete");
finish();
}
});
do {
current = videoView.getCurrentPosition();
// System.out.println("duration - " + duration + " current- " +
// current);
try {
publishProgress((int) (current * 100 / duration));
// System.out.println("time: " + current);
if (current >= 610100 && videoLong == 0) {
System.out.println("video 1 done");
videoView.stopPlayback();
videoView = null;
}
if (current >= 610200 && videoLong == 1) {
System.out.println("video 2 done");
videoView.stopPlayback();
finish();
}
if (current >= 610200 && videoLong == 2) {
System.out.println("video 3 done");
videoView.stopPlayback();
finish();
}
if (mProgressBar.getProgress() >= 100) {
// System.out.println("error100");
}
} catch (Exception e) {
// e.printStackTrace();
}
} while (mProgressBar.getProgress() <= 100);
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
// System.out.println("values: " + values[0]);
mProgressBar.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result) {
System.out.println("on POST execute");
}
}
#Override
public void onBackPressed() {
if (videoView != null)
videoView.stopPlayback();
videoView = null;
System.out.println("back button pressed. stop playback");
super.onBackPressed();
}
Thanks for looking!

Related

AsyncTask is not responding to every click?

I have some problem with Android AsyncTask.In the Fragment i use async task for streaming a audio from url. At first play button it executes without any problem but when i click to go to next song the UI skip the song when i click again in next button then its working fine. It means i have to click two times to execute next button functionality.Here is my async task class:
private class LodingToFetchMp3Url extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setMessage("Loading...!");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
}
#Override
protected String doInBackground(Void... params) {
try {
mediaPlayer.setDataSource(Constants.musicArrayListConstants.get(position).getMp3FileUrl());
mediaPlayer.prepare(); // you must call this method after setup the datasource in setDataSource method. After calling prepare() the instance of MediaPlayer starts load data from URL to internal buffer.
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
mediaFileLengthInMilliseconds = mediaPlayer.getDuration(); // gets the song length in milliseconds from URL
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
imgPlayPause.setBackgroundResource(R.mipmap.btn_pause_black);
} else {
mediaPlayer.pause();
imgPlayPause.setBackgroundResource(R.mipmap.btn_play);
}
primarySeekBarProgressUpdater();
super.onPostExecute(result);
}
}
primarySeekBarProgressUpdater(); method:
private void primarySeekBarProgressUpdater() {
seekBarProgress.setProgress((int) (((float) mediaPlayer.getCurrentPosition() / mediaFileLengthInMilliseconds) * 100)); // This math construction give a percentage of "was playing"/"song length"
if (mediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
primarySeekBarProgressUpdater();
}
};
handler.postDelayed(notification, 100);
}
}
Next Button onClick :
else if (v.getId() == R.id.imgNext) {
if(Constants.dropsModelArrayListConstants.size() > position) {
position = position + 1;
mediaPlayer.pause();
mediaPlayer = new MediaPlayer();
lodingToFetchMp3Url.cancel(true);
lodingToFetchMp3Url = new LodingToFetchMp3Url();
lodingToFetchMp3Url.execute();
}
}

App relaunch state after pressing home button with videoview

I have a video player, when I start it and press launcher icon and again relaunch the app the video start playing from where it was.when I pause the video and press launcher icon and again relaunch the application.video is not in pause state. It again starts from last position.Thanks in advance
public class VideoFullscreenActivity extends Activity {
private static boolean startFromZero = false;
VideoView videoView;
private static boolean isplaying = false;
ProgressDialog pDialog;
SharedPreferences.Editor editor;
SharedPreferences prefs;
int restoredPosition;
public static boolean isStartFromZero() {
return startFromZero;
}
public static void setStartFromZero(boolean startFromZero) {
VideoFullscreenActivity.startFromZero = startFromZero;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_fullscreen);
videoView = (VideoView) findViewById(R.id.videoview);
editor = getSharedPreferences("VIDEO_POSITION", MODE_PRIVATE).edit();
prefs = getSharedPreferences("VIDEO_POSITION", MODE_PRIVATE);
if (startFromZero) {
editor.putInt("CURRENT_POSITION", 0);//stopPosition is an int
editor.commit();
} else {
setStartFromZero(false);
}
restoredPosition = prefs.getInt("CURRENT_POSITION", 0);
if (Utilities.checkInternetConnection(this)) {
Intent intent = getIntent();
pDialog = new ProgressDialog(this);
// Set progressbar message
pDialog.setMessage("Buffering...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
// Show progressbar
pDialog.show();
MediaController mediaController = new
MediaController(this);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
if(intent.getStringExtra(Constants.URL)!= null)
{
Uri videoUri = Uri.parse(intent.getStringExtra(Constants.URL));
videoView.setVideoURI(videoUri);
} else if (intent.getStringExtra("VideoUrl") != null)
{
Map<String, String> headers = new HashMap();
headers.put(APP_KEY, APPKEY_VALUE);
headers.put(SESSION_ID, SharedInstance.getInstance().getLoginDetails().getSessionId());
Uri uri = Uri.parse(intent.getStringExtra("VideoUrl"));
Method setVideoURIMethod = null;
try {
setVideoURIMethod = videoView.getClass().getMethod("setVideoURI", Uri.class, Map.class);
setVideoURIMethod.invoke(videoView, uri,headers);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
//videoView.setVideoURI(uri,headers);
}
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
pDialog.dismiss();
videoView.start();
}
});
if (prefs != null) {
restoredPosition = prefs.getInt("CURRENT_POSITION", 0); //0 is the default value.
}
videoView.seekTo(restoredPosition);
videoView.start();
Log.i("positionPlayback", "onCreate " + restoredPosition);
} else {
Utilities.showAlertLoginDialog(this, "", getResources().getString(R.string.internet_unavailable_msg));
}
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
onBackPressed();
}
});
//---------------------------------------------------------------//
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
this.onPrepared(mediaPlayer);
}
});
}
#Override
public void onPause() {
super.onPause();
Log.i("positionPlayback", "onPause " + restoredPosition);
if (videoView != null && videoView.isPlaying()) {
videoView.pause();
}
restoredPosition = videoView.getCurrentPosition();
editor.putInt("CURRENT_POSITION", restoredPosition);//stopPosition is an int
Utilities.hideKeybord(VideoFullscreenActivity.this);
}
#Override
public void onResume() {
super.onResume();
checkForCrashes();
startFromZero = false;
if (Utilities.checkInternetConnection(this)) {
Log.i("positionPlayback", "onResume " + restoredPosition);
pDialog.show();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
pDialog.dismiss();
restoredPosition = prefs.getInt("CURRENT_POSITION", 0);
videoView.seekTo(restoredPosition);
videoView.start();
}
});
} else {
Utilities.showAlertLoginDialog(this, "", getResources().getString(R.string.internet_unavailable_msg));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
private void checkForCrashes() {
CrashManager.register(this, BuildConfig.hockeyAppId);
}
#Override
protected void onStart() {
super.onStart();
if (prefs != null) {
SharedPreferences prefs = getSharedPreferences("VIDEO_POSITION", MODE_PRIVATE);
restoredPosition = prefs.getInt("CURRENT_POSITION", 0); //0 is the default value.
}
videoView.seekTo(restoredPosition);
videoView.start();
Log.i("positionPlayback", "onStart " + restoredPosition);
}
#Override
protected void onStop() {
super.onStop();
Log.i("positionPlayback", "onStop 1 " + restoredPosition);
if (videoView != null && videoView.isPlaying()) {
videoView.pause();
}
editor.putInt("CURRENT_POSITION", restoredPosition);//stopPosition is an int
editor.commit();
Log.i("positionPlayback", "onStop " + restoredPosition);
}
#Override
protected void onDestroy() {
editor.putInt("CURRENT_POSITION", restoredPosition);
editor.commit();
Log.i("positionPlayback", "onDestroy " + restoredPosition);
super.onDestroy();
}
#Override
protected void onRestart() {
super.onRestart();
SharedPreferences prefs = getSharedPreferences("VIDEO_POSITION", MODE_PRIVATE);
restoredPosition = prefs.getInt("CURRENT_POSITION", 0);
Log.i("positionPlayback", "onRestart " + restoredPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
editor.putInt("CURRENT_POSITION", 0);
editor.commit();
finish();
}
}
Please try to make one status boolean to check video is manual pause or not.
boolean manual_pause = false;
in onPause check video status to affect on manual_pause.
#Override
public void onPause() {
super.onPause();
Log.i("positionPlayback", "onPause " + restoredPosition);
if (videoView != null && videoView.isPlaying()) {
videoView.pause();
manual_pause = false;
} else if(videoView != null){
manual_pause = true;
}
restoredPosition = videoView.getCurrentPosition();
editor.putInt("CURRENT_POSITION", restoredPosition);//stopPosition is an int
Utilities.hideKeybord(VideoFullscreenActivity.this);
}
than check this status in onResume() to set video status previously.
#Override
public void onResume() {
super.onResume();
checkForCrashes();
startFromZero = false;
if (Utilities.checkInternetConnection(this)) {
Log.i("positionPlayback", "onResume " + restoredPosition);
pDialog.show();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
pDialog.dismiss();
restoredPosition = prefs.getInt("CURRENT_POSITION", 0);
videoView.seekTo(restoredPosition);
if(manual_pause) {
videoView.pause();
manual_pause = false;
}else{
videoView.start();
}
}
});
} else {
Utilities.showAlertLoginDialog(this, "", getResources().getString(R.string.internet_unavailable_msg));
}
}
You have to handle your previous status like this manualy.
Hope this will help you...
you are missing editor.commit(); # onPause you need to commit after you add a value!

ProgressBar blocked while MediaPlayer is playing

I'm trying to make a circular progress of the MediaPlayer, so it's indeterminate while it's preparing and setting progress while it's playing.
I've tried a lot of ways, but this is my last one: I update the bar on a AsyncTask<Object, Object, Object>.
The class I'm using is CircularProgressView but I've tried to swap to ProgressBar and the behavior is the same:
public void startPlaying(final Audio audio, final CircularProgressView progress_view) {
if (!isPLAYING) {
progress_view.setIndeterminate(true);
progress_view.setVisibility(View.VISIBLE);
progress_view.startAnimation();
isPLAYING = true;
audioPlaying = audio;
mp = new MediaPlayer();
new AsyncTask<Object, Object, Object>() {
#Override
protected Object doInBackground(Object... objects) {
try {
mp.prepare();
publishProgress((int)-1);
mediaFileLengthInMilliseconds = mp.getDuration();
mp.start();
while (mp != null && mp.isPlaying()) {
Thread.sleep(100);
publishProgress((int) (mp.getCurrentPosition()));
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
mp.setDataSource(audio.getFile().getUrl());
} catch (IOException e) {
e.printStackTrace();
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
stopPlaying();
publishProgress((int)-2);
}
});
}
#Override
protected void onProgressUpdate(Object... values) {
super.onProgressUpdate(values);
int value = (int)values[0];
if (value == -1) {
progress_view.setIndeterminate(false);
progress_view.setMaxProgress(mediaFileLengthInMilliseconds);
} else if (value == -2) {
progress_view.setVisibility(View.GONE);
} else {
progress_view.setProgress((int) values[0]);
System.out.println("setting: " + values[0]);
}
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
}
}.execute();
} else {
isPLAYING = false;
stopPlaying();
}
}
on debug, the ProgressBar or CircularProgressView .setProgress() is called during the audio reproduction, but it remains blocked in indeterminate, but progress_view.setIndeterminate(false) is called as well, and it doesn't become indeterminate.
When the audio finishes, the ProgressBar or CircularProgressView gets 100% progress.
Any clue?
Thank you very much in advance.
EDIT:
as #Blackbelt suggested, I had to call mediaFileLengthInMilliseconds = mp.getDuration(); before publishProgress((int)-1);
but now this is the behavior:
https://drive.google.com/file/d/0B-V0KHNRjbE_b3hkbkwtTXhIeTg/view?usp=sharing
EDIT 2: Log of mp.getDuration() and mp.getCurrentPosition():
http://pastebin.com/g93V5X9F
or maybe this is more clear:
http://pastebin.com/kYm01Gpg
called on this part:
#Override
protected void onProgressUpdate(Object... values) {
super.onProgressUpdate(values);
int value = (int)values[0];
if (value == -1) {
progress_view.setIndeterminate(false);
progress_view.setMaxProgress(mediaFileLengthInMilliseconds);
Log.i("Stackoverflow:", "setMaxProgress to " + mediaFileLengthInMilliseconds);
} else if (value == -2) {
progress_view.setVisibility(View.GONE);
} else {
progress_view.setProgress((int) values[0]);
Log.i("Stackoverflow:", "setProgress to " + (int)values[0]);
}
}
EDIT 3: I'm adding the new code, commenting out the functions setIndeterminate(boolean) and swapping into ProgressBar:
XML:
<ProgressBar
android:id="#+id/progress_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="false"
android:progress="40"
android:visibility="gone"
android:layout_alignTop="#+id/play_button"
android:layout_alignLeft="#+id/play_button"
android:layout_alignStart="#+id/play_button"
android:layout_alignRight="#+id/play_button"
android:layout_alignEnd="#+id/play_button"
android:layout_alignBottom="#+id/play_button" />
Java:
public void startPlaying(final Audio audio, final ProgressBar progress_view) {
if (!isPLAYING) {
Log.i("Stackoverflow", "startPlaying called");
audio.put("times_listened", audio.getTimes_Listened() + 1);
audio.saveEventually();
progress_view.setVisibility(View.VISIBLE);
isPLAYING = true;
audioPlaying = audio;
mp = new MediaPlayer();
new AsyncTask<Object, Object, Object>() {
#Override
protected Object doInBackground(Object... objects) {
try {
mp.prepare();
mediaFileLengthInMilliseconds = mp.getDuration();
publishProgress((int)-1);
mp.start();
while (mp != null && mp.isPlaying()) {
Thread.sleep(100);
publishProgress((int) (mp.getCurrentPosition()));
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
mp.setDataSource(audio.getFile().getUrl());
} catch (IOException e) {
e.printStackTrace();
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
stopPlaying();
publishProgress((int)-2);
}
});
}
#Override
protected void onProgressUpdate(Object... values) {
super.onProgressUpdate(values);
int value = (int)values[0];
if (value == -1) {
progress_view.setMax(mediaFileLengthInMilliseconds);
Log.i("Stackoverflow:", "setMaxProgress to " + mediaFileLengthInMilliseconds);
} else if (value == -2) {
progress_view.setVisibility(View.GONE);
} else {
progress_view.setProgress((int) values[0]);
Log.i("Stackoverflow:", "setProgress to " + (int)values[0]);
System.out.println("setting: " + values[0]);
}
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
}
}.execute();
} else {
isPLAYING = false;
stopPlaying();
}
}
EDIT 4:
I'm calling progress_view.isDeterminate() and it's returning me true everytime. So I decided to do when modifying the progress:
#Override
protected void onProgressUpdate(Object... values) {
super.onProgressUpdate(values);
int value = (int)values[0];
if (value == -1) {
progress_view.setMax(mediaFileLengthInMilliseconds);
Log.i("Stackoverflow:", "setMaxProgress to " + mediaFileLengthInMilliseconds);
} else if (value == -2) {
progress_view.setVisibility(View.GONE);
} else {
if (progress_view.isIndeterminate()) // LOOK AT THIS
progress_view.setIndeterminate(false);
progress_view.setProgress((int) values[0]);
Log.i("Stackoverflow:", "setProgress to " + (int) values[0]);
Log.i("Stackoverflow", "Indeterminate state: " + progress_view.isIndeterminate());
System.out.println("setting: " + values[0]);
}
}
and the output is always:
Indeterminate state: true
*WHY ? * :'(
Probably you want to call mediaFileLengthInMilliseconds = mp.getDuration(); before calling publishProgress((int)-1); and not after, or not using that member at all, since you keep already the MediaPlayer as member, you could query directly it.
Edit
To fix the problem in your video, you have to use the following style style="#android:style/Widget.ProgressBar.Horizontal. With the circular ProgressBar, the setIndetermiate flag is ignored

MediaPlayer.prepare() THROWS illegeal state exception

I am trying to stream a Video in android. For one uri it works fine if i go to another it throws illegalstateexception. Actually my code is
public class VideoSample extends Activity implements OnSeekBarChangeListener, Callback, OnPreparedListener, OnCompletionListener, OnBufferingUpdateListener,
OnClickListener, OnSeekCompleteListener, AnimationListener {
private TextView textViewPlayed;
private TextView textViewLength;
private SeekBar seekBarProgress;
private SurfaceView surfaceViewFrame;
private ImageView imageViewPauseIndicator;
private MediaPlayer player;
private SurfaceHolder holder;
private ProgressBar progressBarWait;
private Timer updateTimer;
private Bundle extras;
private Animation hideMediaController;
private LinearLayout linearLayoutMediaController;
private static final String TAG = "androidEx2 = VideoSample";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videosample);
extras = getIntent().getExtras();
linearLayoutMediaController = (LinearLayout) findViewById(R.id.linearLayoutMediaController);
linearLayoutMediaController.setVisibility(View.GONE);
hideMediaController = AnimationUtils.loadAnimation(this, R.anim.disapearing);
hideMediaController.setAnimationListener(this);
imageViewPauseIndicator = (ImageView) findViewById(R.id.imageViewPauseIndicator);
imageViewPauseIndicator.setVisibility(View.GONE);
if (player != null) {
if (!player.isPlaying()) {
imageViewPauseIndicator.setVisibility(View.VISIBLE);
}
}
textViewPlayed = (TextView) findViewById(R.id.textViewPlayed);
textViewLength = (TextView) findViewById(R.id.textViewLength);
surfaceViewFrame = (SurfaceView) findViewById(R.id.surfaceViewFrame);
surfaceViewFrame.setOnClickListener(this);
surfaceViewFrame.setClickable(false);
seekBarProgress = (SeekBar) findViewById(R.id.seekBarProgress);
seekBarProgress.setOnSeekBarChangeListener(this);
seekBarProgress.setProgress(0);
progressBarWait = (ProgressBar) findViewById(R.id.progressBarWait);
holder = surfaceViewFrame.getHolder();
holder.addCallback(this);
player = new MediaPlayer();
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnBufferingUpdateListener(this);
player.setOnSeekCompleteListener(this);
player.setScreenOnWhilePlaying(true);
}
private void playVideo() {
if (extras.getString("video_path").equals("VIDEO_URI")) {
showToast("Please, set the video URI in HelloAndroidActivity.java in onClick(View v) method");
} else {
new Thread(new Runnable() {
public void run() {
try {
player.setDataSource(extras.getString("video_path"));
Log.i(TAG, extras.getString("video_path"));
player.prepare();
} catch (IllegalArgumentException e) {
showToast("Error while playing video Argument");
Log.i(TAG, "========== IllegalArgumentException ===========");
e.printStackTrace();
} catch (IllegalStateException e) {
showToast("Error while playing video State");
Log.i(TAG, "========== IllegalStateException ===========");
e.printStackTrace();
} catch (IOException e) {
showToast("Error while playing video. Please, check your network connection.");
Log.i(TAG, "========== IOException ===========");
e.printStackTrace();
}
}
}).start();
}
}
private void showToast(final String string) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(VideoSample.this, string, Toast.LENGTH_LONG).show();
finish();
}
});
}
private void hideMediaController() {
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
public void run() {
linearLayoutMediaController.startAnimation(hideMediaController);
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
Log.i(TAG, "========== onProgressChanged : " + progress + " from user: " + fromUser);
if (!fromUser) {
textViewPlayed.setText(Utils.durationInSecondsToString(progress));
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
if (player.isPlaying()) {
progressBarWait.setVisibility(View.VISIBLE);
player.seekTo(seekBar.getProgress() * 1000);
Log.i(TAG, "========== SeekTo : " + seekBar.getProgress());
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
}
public void surfaceCreated(SurfaceHolder holder) {
player.setDisplay(holder);
playVideo();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
public void onPrepared(MediaPlayer mp) {
Log.i(TAG, "========== onPrepared ===========");
int duration = mp.getDuration() / 1000; // duration in seconds
seekBarProgress.setMax(duration);
textViewLength.setText(Utils.durationInSecondsToString(duration));
progressBarWait.setVisibility(View.GONE);
// Get the dimensions of the video
int videoWidth = player.getVideoWidth();
int videoHeight = player.getVideoHeight();
float videoProportion = (float) videoWidth / (float) videoHeight;
Log.i(TAG, "VIDEO SIZES: W: " + videoWidth + " H: " + videoHeight + " PROP: " + videoProportion);
// Get the width of the screen
int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
int screenHeight = getWindowManager().getDefaultDisplay().getHeight();
float screenProportion = (float) screenWidth / (float) screenHeight;
Log.i(TAG, "VIDEO SIZES: W: " + screenWidth + " H: " + screenHeight + " PROP: " + screenProportion);
// Get the SurfaceView layout parameters
android.view.ViewGroup.LayoutParams lp = surfaceViewFrame.getLayoutParams();
if (videoProportion > screenProportion) {
lp.width = screenWidth;
lp.height = (int) ((float) screenWidth / videoProportion);
} else {
lp.width = (int) (videoProportion * (float) screenHeight);
lp.height = screenHeight;
}
// Commit the layout parameters
surfaceViewFrame.setLayoutParams(lp);
// Start video
if (!player.isPlaying()) {
player.start();
updateMediaProgress();
linearLayoutMediaController.setVisibility(View.VISIBLE);
hideMediaController();
}
surfaceViewFrame.setClickable(true);
}
public void onCompletion(MediaPlayer mp) {
mp.stop();
if (updateTimer != null) {
updateTimer.cancel();
}
finish();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
player.release();
}
/**
* Change progress of mediaController
* */
private void updateMediaProgress() {
updateTimer = new Timer("progress Updater");
updateTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
seekBarProgress.setProgress(player.getCurrentPosition() / 1000);
}
});
}
}, 0, 1000);
}
public void onBufferingUpdate(MediaPlayer mp, int percent) {
int progress = (int) ((float) mp.getDuration() * ((float) percent / (float) 100));
seekBarProgress.setSecondaryProgress(progress / 1000);
}
public void onClick(View v) {
if (v.getId() == R.id.surfaceViewFrame) {
if (linearLayoutMediaController.getVisibility() == View.GONE) {
linearLayoutMediaController.setVisibility(View.VISIBLE);
hideMediaController();
} else if (player != null) {
if (player.isPlaying()) {
player.pause();
imageViewPauseIndicator.setVisibility(View.VISIBLE);
} else {
player.start();
imageViewPauseIndicator.setVisibility(View.GONE);
}
}
}
}
public void onSeekComplete(MediaPlayer mp) {
progressBarWait.setVisibility(View.GONE);
}
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
}
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
public void onAnimationStart(Animation animation) {
linearLayoutMediaController.setVisibility(View.GONE);
}
}
This is the working uri http://www.pocketjourney.com/downloads/pj/video/famous.3gp
This one throws illegalstateexception at mp.prepare() http://www.fieldandrurallife.tv/videos/Benltey%20Mulsanne.mp4
In order to stream video on android devices, you can use VideoView class.
The VideoView class can load images from various sources, takes care of computing its measurement from the video so that it can be used in any layout manager, and provides various display options such as scaling and tinting.
i've tried the video that gave you an error and it worked well.
You will find below the code that I've used to test your link for streaming the video:
VideoView videoview;
videoview = (VideoView) findViewById(R.id.VideoView);
try {
MediaController mediacontroller = new MediaController(VideoViewerActivity.this);
mediacontroller.setAnchorView(videoview);
Uri video = Uri.parse("http://www.fieldandrurallife.tv/videos/Benltey%20Mulsanne.mp4");
videoview.setMediaController(mediacontroller);
videoview.setVideoURI(video);
} catch (Exception e) {
e.printStackTrace();
}
videoview.requestFocus();
videoview.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
videoview.setZOrderOnTop(true);
videoview.start();
}
});
And don't forget to put the videoView in your .xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<VideoView
android:id="#+id/VideoView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
If you have any question related to my answer, do not hesitate to contact me.
Good luck
As you are getting illegal state exception for player.prepare(), you can try restarting MediaPlayer object in respective catch block like in below code snippet. (Also its better to call start() only after mediaPlayer is prepared):
try{
player.prepare();
}catch (IllegalStateException e) {
player = new MediaPlayer();
player.setDataSource(extras.getString("video_path"));
Log.i(TAG, extras.getString("video_path"));
player.prepare();
player.setOnPreparedListener(new OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp){
mp.start();
}
});
}

How to display text underneath playing video in android?

I am developing an application in which I used VideoView to play a video. What I want is I need to display some text underneath the playing video and the text should be changed as the video plays I mean depending on elapsed time. Like SRT. So, How to get elapsed time of video in android? And when we pause the video according text should be paused as well and after that when we resume video the text and the following text should be displayed.
Any help would be appreciated.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.playing);
mVideoView = (VideoView)findViewById(R.id.VideoView);
uri = Uri.parse("android.resource://com.abhan.video/" + R.raw.abhan);
Date dt = new Date();
mHours = dt.getHours();
mMinutes = dt.getMinutes();
mSeconds = dt.getSeconds();
String curTime = mHours + ":"+ mMinutes + ":" + mSeconds;
mVideoView.setVideoURI(uri);
mVideoView.start();
Runnable runnable = new CountDownRunner();
myThread= new Thread(runnable);
myThread.start();
mVideoView.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
Log.i("TAG", "On Prepared");
}
});
mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
Log.v("TAG", "On Completion");
myThread.stop();
Intent i = new Intent(Playing.this, VideoPlay.class);
startActivity(i);
finish();
}
});
}
class CountDownRunner implements Runnable {
public void run() {
while(!Thread.currentThread().isInterrupted()) {
try {
doWork();
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
public void doWork() {
runOnUiThread(new Runnable() {
public void run() {
try {
mText = (TextView)findViewById(R.id.SetText);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String curTime = hours + ":"+ minutes + ":" + seconds;
if(minutes == mMinutes && seconds == mSeconds) {
mText.setText(getString(R.string.one));
} else if(minutes == mMinutes && seconds == mSeconds+20) {
mText.setText(getString(R.string.two));
} else if(minutes == mMinutes && seconds == mSeconds+38) {
mText.setText(getString(R.string.three));
} else if(minutes == mMinutes && seconds == mSeconds+47) {
mText.setText(getString(R.string.four));
} else if(minutes == mMinutes+1 && seconds == mSeconds2+2) {
mText.setText(getString(R.string.five));
} else if(minutes == mMinutes+1 && seconds == mSeconds2+22) {
mText.setText(getString(R.string.six));
} else if(minutes == mMinutes+2) {
mText.setText(getString(R.string.seven));
} else if(minutes == mMinutes+2 && seconds == mSeconds2+2) {
mText.setText("");
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((!(android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.DONUT)
&&keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0))
{
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}
public void onBackPressed() {
Intent intent = new Intent(Playing.this, VideoPlay.class);
intent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(intent);
finish();
return;
}
Thanks.
Isn't it VideoView's getCurrentPosition() what you are looking for?
To change the contents of your TextView (or whatever yo want to use), I would set a Timer, with enough frecuency to update your "subtitle". Its TimerTask could get the playback time with that getCurrentPosition(), and use a Map to store messages values and the time as the key.
Here it's and example of what I'm thinking:
00 - "Video begins!"
05 - "something funny happens"
12 - "Video ends!"
class MySubtitlePoster extends TimerTask{
private VideoView video;
private TreeMap <Integer, String> messages; // populate it somewhere
public MySubtitlePoster(VideoView v) {
video = v;
}
public void run() {
int videoPos = video.getCurrentPosition();
String messageToDisplay = messages.floorKey(new Integer(videoPos));
// If all this is right, now you can get the message and post it, probably using a Handler
}
}
==========================================
After seeing your complete code, I can give you more detailed tips, but the coding thing is your job, so...
To create the map:
messages = new TreeMap();
messages.put(new Integer(0), getString(R.string.one));
messages.put(new Integer(20), getString(R.string.two));
...
messages.put(new Integer(62), getString(R.string.four));
To do the work:
public void doWork(){
runOnUiThread(new Runnable() {
public void run() {
try{
mText = (TextView)findViewById(R.id.SetText);
//If it returns milliseconds, divide by 1000
int playTime = mVideoView.getCurrentPosition();
String textValue = messages.ceilingEntry(new Integer(playtime)).getValue();
mText.setText(textValue);
}catch (Exception e) {
e.printStackTrace();
}
}
});
}
And finally, use a Timer instead of this (There is an article here about Timers and UI):
public void run()
{
while(!Thread.currentThread().isInterrupted())
{
try
{
doWork();
Thread.sleep(1000);
}catch (InterruptedException e)
{
Thread.currentThread().interrupt();
e.printStackTrace();
}catch(Exception e)
{
e.printStackTrace();
}
}
}
It is really ugly and inefficient .
So, happy coding, and please if you find some inccurancy try to solve it yourself, not because I'm not kind on helping, but it's your best chance to improve your skills.
Regards, Manuel.

Categories

Resources