I Want to pause my video play after 4 seconds of playing, then I want to pop up a message to the user. Can someone point me in the right direct how to pause the video after 4 seconds please. Thanks
V2 Implemented #gogothebee feedback {Now the video pause at position 0 (before it actually start).
public class PlayVideoActivity extends ActionBarActivity {
public static final String TAG = PlayVideoActivity.class.getSimpleName();
Bundle bunde;
Intent intent;
String content_actual_content;
VarController vc = new VarController(PlayVideoActivity.this);
public ImageLoader imageLoader;
private VideoView mVideoView;
private MediaController mMediaController;
ProgressBar pbplay1;
private boolean isActive;
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_video); //playvideo (FullScreen)
handler = new Handler();
//Hide Action Bar
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
//Toast.makeText(PlayVideoActivity.this, "You're on Video Player with link: " + content_actual_content, Toast.LENGTH_SHORT).show();
//Set ProgressBar
pbplay1 = (ProgressBar) findViewById(R.id.pbplay1);
//Get Link from ImageAdapter
intent = this.getIntent();
bunde = intent.getExtras();
content_actual_content = bunde.getString("content_actual_content");
Toast.makeText(PlayVideoActivity.this, "You're on Video Player with link: " + content_actual_content, Toast.LENGTH_SHORT).show();
//Initiate Player
mVideoView = (VideoView) findViewById(R.id.videoview);
mVideoView.setVideoURI(Uri.parse(content_actual_content));
mVideoView.setMediaController(new MediaController(PlayVideoActivity.this));
mVideoView.requestFocus();
mVideoView.setMediaController(mMediaController);
//new myAsync().execute();
}//--- end onCreate
#Override
protected void onPause() {
super.onPause();
isActive = false;
}
#Override
protected void onResume() {
super.onResume();
isActive = true;
mVideoView.requestFocus();
mVideoView.start();
scheduleVideoPause(4000);
}
private void scheduleVideoPause(int msec) {
handler.removeCallbacksAndMessages(null);
handler.postDelayed(new Runnable() {
#Override
public void run() {
if(!isActive) {
return;
}
mVideoView.pause();
Toast.makeText(PlayVideoActivity.this, "Video has PAUSED at: " + mVideoView.getCurrentPosition(), Toast.LENGTH_SHORT).show();
}
}, msec);
}
V1
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_video); //playvideo (FullScreen)
//Hide Action Bar
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
//Toast.makeText(PlayVideoActivity.this, "You're on Video Player with link: " + content_actual_content, Toast.LENGTH_SHORT).show();
//Set ProgressBar
pbplay1 = (ProgressBar) findViewById(R.id.pbplay1);
//Get Link from ImageAdapter
intent = this.getIntent();
bunde = intent.getExtras();
content_actual_content = bunde.getString("content_actual_content");
Toast.makeText(PlayVideoActivity.this, "You're on Video Player with link: " + content_actual_content, Toast.LENGTH_SHORT).show();
//Initiate Player
mVideoView = (VideoView) findViewById(R.id.videoview);
mVideoView.setVideoURI(Uri.parse(content_actual_content));
mMediaController = new MediaController(PlayVideoActivity.this);
mVideoView.setMediaController(mMediaController);
mVideoView.requestFocus();
mVideoView.start();
//new myAsync().execute();
Log.i("**********************", "getCurrentPosition: " + mVideoView.getCurrentPosition());
if (mVideoView.getCurrentPosition() == 4000) {
mVideoView.pause();
Toast.makeText(PlayVideoActivity.this, "Video has PAUSED at: " + mVideoView.getCurrentPosition(), Toast.LENGTH_SHORT).show();
}
}//--- end onCreate
It seems that there's no way to do it easily. However, my solution is to spawn a background timer that runs every 100ms (adjustable) and check the current position. Once it is past the desired threshold (4000ms in this case), the video is stopped. I know it's not elegant and won't work exactly at 4000ms, but if anyone has a better idea, please share it. When adjusting the pooling interval in case you want to get as close as possible to 4000ms, don't go too low for performance reasons.
This solution can also be refactored as it's quite messy, but I wanted to show the concept in as little code as possible.
private Timer timer;
private boolean isActive;
private VideoView mVideoView;
private final static int POOLING_INTERVAL_MS = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initiate Player
mVideoView = (VideoView) findViewById(R.id.videoview);
mVideoView.setVideoURI(Uri.parse("Your-Video-URI"));
mVideoView.setMediaController(new MediaController(this));
}
#Override
protected void onPause() {
super.onPause();
isActive = false;
cancelProgressPooling();
}
#Override
protected void onResume() {
super.onResume();
isActive = true;
mVideoView.requestFocus();
mVideoView.start();
initVideoProgressPooling(4000);
}
private void initVideoProgressPooling(final int stopAtMsec) {
cancelProgressPooling();
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
mVideoView.post(new Runnable() {
#Override
public void run() {
if (!isActive) {
cancelProgressPooling();
return;
}
if(mVideoView.getCurrentPosition() >= stopAtMsec) {
mVideoView.pause();
cancelProgressPooling();
Toast.makeText(MainActivity.this, "Video has PAUSED at: " + mVideoView.getCurrentPosition(), Toast.LENGTH_SHORT).show();
}
}
});
}
}, 0, POOLING_INTERVAL_MS);
}
private void cancelProgressPooling() {
if(timer != null) {
timer.cancel();
}
timer = null;
}
Related
I am developing an android application which will play live radio audio stream. I have implemented android media player for this purpose which constantly receives the audio data from a remote source.
The play button will show a buffering ProgressDialog to the user on click of it and will start the media player. I am successful in doing all so, but the only problem that I face is that I want to notify the user if the media player is unable to load audio content from the streaming server. Is there a timeout or some sort of an error that I can catch? Nothing is currently being thrown, if media player is unable to load audio content form server:
My code looks like:
public class MainActivity extends AppCompatActivity
{
Button playbtn_flat,stopbtn_flat;
static MediaPlayer mPlayer;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playbtn_flat = (Button) findViewById(R.id.play_button);
stopbtn_flat = (Button) findViewById(R.id.stop_button);
playbtn_flat.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
listen_live("http://192.168.**.***:port/mountpoint");
}
});
stopbtn_flat.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (mPlayer != null && mPlayer.isPlaying()) {
mPlayer.stop();
}
}
});
}
void listen_live(String stream_ip) {
try {
final ProgressDialog progressDialog = ProgressDialog.show(MainActivity.this, "Please Wait...", "Buffering");
mPlayer = new MediaPlayer();
final MediaPlayer.OnPreparedListener onPreparedListener = new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
mp.start();
}
};
final MediaPlayer.OnErrorListener onErrorListener = new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra)
{
Log.e("abc", String.format("Error(%s%s)", what, extra));
return false;
}
};
final Handler onPreparedHandle = new Handler() {
#Override
public void handleMessage(Message msg) {
mPlayer.setOnErrorListener(onErrorListener); // set onErrorListener
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
onPreparedListener.onPrepared(mPlayer);
}
};
final String url = stream_ip;
new Thread() {
#Override
public void run() {
mPlayer = MediaPlayer.create(MainActivity.this, Uri.parse(url)); // create new instance of MediaPlayer and prepare it
onPreparedHandle.sendMessage(onPreparedHandle.obtainMessage()); // send message to main thread
}
}.start();
} catch (Exception e) {
Log.e("abc ", e.toString());
}
}
}
I am loading video from async task. When video took too long to load then back press to cancel.
My code here
public class LiveStreaming extends AppCompatActivity {
VideoView videoView;
private myAsync sync;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_live_streaming);
String videourl = getIntent().getStringExtra("Link");
videoView = (VideoView) findViewById(R.id.videoStreaming);
progressDialog = ProgressDialog.show(this, "",
"Loading TV...", true);
progressDialog.setCancelable(false);
// progressDialog.dismiss();
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);
Uri video = Uri.parse(videourl);// insert video url
videoView.setMediaController(mediaController);
videoView.setVideoURI(video);
videoView.requestFocus();
sync = new myAsync();
sync.execute();
// PlayVideo();
}
private class myAsync extends AsyncTask<Void, Integer, Void> {
int duration = 0;
int current = 0;
private volatile boolean running = true;
#Override
protected void onCancelled() {
running = true;
}
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
progressDialog.dismiss();
videoView.start();
duration = videoView.getDuration();
}
});
do {
current = videoView.getCurrentPosition();
System.out.println("duration - " + duration + " current- "
+ current);
if (sync.isCancelled())
break;
}
while (current != duration || current == 0);
return null;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
if (sync!=null){
this.finish();
}
}
}
I debugged my app.
When back pressed then method wasn't called. I don't know what is the problem
Thank you
remove super.onBackPressed(); for onBackPressed() to work.And to cancel the async you can call sync.cancel()
Declare your async task in your activity.
private YourAsyncTask mTask;
Instantiate your async task where you want to use
mTask = new YourAsyncTask().execute();
And then cancel where you want to stop the task
mTask.cancel(true);
Hope this helps
I Use MediaController to play my audio. But, I want to remove Backward & Forward Button from my MediaController. Please, help me. (PS. A Code is be useful) How can I edit it.
public class Main extends Activity implements MediaPlayerControl {
private static final String PLAY_AUDIO = "PLAY_AUDIO";
private MediaController mMediaController
private MediaPlayer mMediaPlayer;
private Handler mHandler = new Handler();
static Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this;
mMediaPlayer = new MediaPlayer();
mMediaController = new MediaController(this);
mMediaController.setMediaPlayer(Main.this);
mMediaController.setAnchorView(findViewById(R.id.audioView));
mMediaController.setPrevNextListeners(new View.OnClickListener() {
public void onClick(View v) {
//next button clicked
}
}, new View.OnClickListener() {
public void onClick(View v) {
//previous button clicked
}
});
try {
mMediaPlayer.setDataSource(
this,
Uri.parse("android.resource://com.app.audioplayer/raw/allforyou")
);
mMediaPlayer.prepare();
} catch (IOException e) {
Log.e(PLAY_AUDIO, "Could not open file " + " " + " for playback.", e);
}
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mHandler.post(new Runnable() {
public void run() {
mMediaController.show(0);
mMediaPlayer.start();
}
});
}
});
}
}
Simplest solution ...
MediaController mediaController = new MediaController(this, false);
Courtesy : #Meow meo (in comments of original question)
For custom videoview I had to override the MediaController (to change the design of the buttons and connect to the buttons pause / play a selector). The situation is this: put the video on pause and turning the application, and then again restored, the video starts playing again, and not from the point at which it was suspended, and therefore the question arose: how to make the video starts playing from the place , where it was stopped? What do I need to change in the VideoActivity?
public class VideoActivity extends Activity {
VideoView videoView;
VkMediaController mc;
private static final String CURRENT = "duration";
private static final String URL = "url";
private Uri mURI;
private int mCurrentPosition = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.video_view_player);
videoView = (VideoView) findViewById(R.id.videoViewplayer);
mc = new VkMediaController(this);
mURI = getIntent().getData();
if (savedInstanceState != null) {
mURI = Uri.parse(savedInstanceState.getString(URL));
mCurrentPosition = savedInstanceState.getInt(CURRENT);
}
videoView.setMediaController(mc);
videoView.setVideoURI(mURI);
videoView.requestFocus();
}
#Override
protected void onStart() {
super.onStart();
videoView.start();
if (mCurrentPosition != -1) {
videoView.seekTo(mCurrentPosition);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt(CURRENT, videoView.getCurrentPosition());
outState.putString(URL, mURI.toString());
super.onSaveInstanceState(outState);
}
}
I think the problem is that videoView.getCurrentPosition() will always return 0 when you call inside onSaveInstanceState(Bundle outState), cos at that time the video already reset, so call videoView.getCurrentPosition() when onPause(), this will return you the desired value.
I had the same problem. I thought I did everything right but it didnt work. Then I just changed the order so I first call VideoView.seekTo() and then VideoView.start() . That worked.
I also have VideoView.requestFocus() in there but I dont know if that matters.
videoPlayer.requestFocus();
videoPlayer.seekTo(position);
videoPlayer.start();
So if youre sure you position variable has the right value, this might be your answer.
You may not be able to seek when the Video is not loaded. Implement onPreparedListener like this:
public class VideoActivity extends Activity implements OnPreparedListener {
VideoView videoPlayer;
int position;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState!=null){
position=savedInstanceState.getInt("pos")
}
// setting up the videoview
setContentView(R.layout.activity_video);
getIntent().getExtras().getString("url");
Uri videouri = Uri.parse(getIntent().getExtras().getString("url"));
videoPlayer = (VideoView) findViewById(R.id.videoView);
videoPlayer.setOnPreparedListener(this);
videoPlayer.setKeepScreenOn(true);
videoPlayer.setVideoURI(videouri);
}
/**
* Start the plaback when the video is loaded
*
* #param mp
* #see android.media.MediaPlayer.OnPreparedListener#onPrepared(android.media.MediaPlayer)
*/
public void onPrepared(MediaPlayer mp) {
//this is a TextView infront of the VideoView which tells the User the Video is loading- hide that
findViewById(R.id.tv_video_load).setVisibility(View.GONE);
videoPlayer.requestFocus();
videoPlayer.seekTo(position)
videoPlayer.start();
}
}
Portrait to LandScape LifeCycle Demo
VideoView videoView;
int lastPosition;
int Video_STATE_POSITION = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null)
{
String message = savedInstanceState.getString("message");
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
lastPosition=savedInstanceState.getInt("STATE_POSITION");
videoView.seekTo(lastPosition);
videoView.start();
Log.e("Keshav", "MainActivity onCreate() is called savedInstanceState lastPosition->" + lastPosition);
}
}
#Override
public void onSaveInstanceState(Bundle outState)
{
outState.putString("message", "This is my message to be reloaded");
outState.putInt("STATE_POSITION", Video_STATE_POSITION);
super.onSaveInstanceState(outState);
}
#Override
protected void onPause() {
super.onPause();
Video_STATE_POSITION = videoView.getCurrentPosition();
Log.e("Keshav", "MainActivity onPause is called ->" +Video_STATE_POSITION);
}
I am playing a video when I click on a button. But at that time a flicker (black flash) is coming before and after that video clip. Any suggestions. Thanks in advance
Below is my code
babyFace=(ImageView)findViewById(R.id.babyFace);
lEye =(ImageView)findViewById(R.id.lEye);
lEye.setOnClickListener(DisplayListener);
private OnClickListener DisplayListener=new OnClickListener (){
#Override
public void onClick(View image) {
videoView.setVideoURI(Uri.parse("android.resource://com.babypalyface/raw/mdpi_l_dimple");
playVideo();
}
private void playVideo()
{
videoView.setVisibility(View.VISIBLE);
videoView.requestFocus();
videoView.start();
videoView.setOnCompletionListener(VideoViewListener);
}
OnCompletionListener VideoViewListener=new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp) {
videoView.destroyDrawingCache();
videoView.clearFocus();
videoView.setVisibility(View.GONE);
}
};
Modify below code to play your video. Suggest you .. before showing the content to user give some time to download few bytes of content. Hope this helps
public class PlayVideo extends Activity{
ProgressDialog dialog;
int increment;
VideoView video;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
video = (VideoView)findViewById(R.id.VideoView01);
MediaController mc = new MediaController(this);
video.setMediaController(mc);
video.setVideoPath("rtsp://v5.cache8.c.youtube.com/CjYLENy73wIaLQnAHrGa4Moc0RMYESARFEIJbXYtZ29vZ2xlSARSBWluZGV4YO7F8s7Fh92ZTAw=/0/0/0/video.3gp");
increment = 1;
dialog = new ProgressDialog(this);
dialog.setCancelable(true);
dialog.setMessage("Loading...");
// set the progress to be horizontal
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
// reset the bar to the default value of 0
dialog.setProgress(0);
int maximum = 100;
// set the maximum value
dialog.setMax(maximum);
// display the progressbar
dialog.show();
// create a thread for updating the progress bar
Thread background = new Thread(new Runnable() {
public void run() {
try {
Looper.prepare();
Thread.sleep(20000);
progressHandler
.sendMessage(progressHandler.obtainMessage());
} catch (java.lang.InterruptedException e) {
// if something fails do something smart
}
Looper.loop();
}
});
// start the background thread
background.start();
}
// handler for the background updating
Handler progressHandler = new Handler() {
public void handleMessage(Message msg) {
dialog.incrementProgressBy(increment);
dialog.dismiss();
video.start();
}
};
}