flicker is coming before and after playing a video clip - android

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();
}
};
}

Related

Detecting buffering error (or time_out) if media player is unable to load audio content from server

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());
}
}
}

Android Cancel Async task when back pressed

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

Remove Backward & Forward Button From Media Controller

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)

Why won't ProgressDialog show properly?

My ProgressDialog will not show up. In my program the user selects bitrate from a pop up menu, the content is fetched online and displayed in VideoView.
However, all I get is a black screen while the video loads and the progressDialog is display for a split second (or less) at end before the video finally loads.
private void showPopupMenu(View v){
popupMenu = new PopupMenu(VideoPlayer.this, v);
if(bitRates != null){
int menuItem = 0;
int index = bitRates.size()-1;
popupMenu.getMenu().add(0,menuItem, 0,"Hide menu");
for(int i=1;i<bitRates.size();i++){
menuItem = i;
popupMenu.getMenu().add(0,menuItem, 0,"Quality"+" : "+bitrateCheck(bitRates.get(index))).setCheckable(true);
Log.i("ITEM",qualityList.get(i)+" : "+bitRates.get(i));
index--;
}
popupMenu.getMenu().add(0,menuItem++, 0,"Catalog");
}
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(final MenuItem item) {
p_dialog = ProgressDialog.show(VideoPlayer.this, "", "Loading...");
//get current position of video to seek to
final int position = mVideoView.getCurrentPosition();
new Thread() {
public void run() {
try{
runOnUiThread(new Runnable() {
public void run() {
if(item.getTitle().equals("Catalog")){
backButtonVideo(new View(VideoPlayer.this));
}
else if(item.getTitle().equals("Hide menu")){
popupMenu.dismiss();
mVideoView.start();
}
else{
play(streamUrls.get(item.getItemId()),position);
}
}
});
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
p_dialog.dismiss();
}
}.start();
return true;
}
});
}
public void play(String _videoUri, int position){
Log.i(TAG,"URI is : "+Uri.parse(_videoUri).toString());
//View view = new View()
MediaController mc = new MediaController(VideoPlayer.this);
mVideoView.setMediaController(mc);
mVideoView.setVideoURI(Uri.parse(_videoUri));
mVideoView.requestFocus();
mVideoView.seekTo(position);
mVideoView.start();
}
////////////////////////Edit with new Code: as per suggestions/////////////////////
Now the dialog does not show at all.
mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
mVideoView.start();
}
});
///////////////////////////////////////////////////////////////////////////////////
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(final MenuItem item) {
//get current position of video to seek to
final int position = mVideoView.getCurrentPosition();
p_dialog = ProgressDialog.show(VideoPlayer.this, "", "Loading...");
try{
if(item.getTitle().equals("Catalog")){
backButtonVideo(new View(VideoPlayer.this));
}
else if(item.getTitle().equals("Hide menu")){
popupMenu.dismiss();
mVideoView.start();
}
else{
play(streamUrls.get(item.getItemId()),position);
}
}
catch (Exception e) {Log.e("tag", e.getMessage());}
return true;
}
});
}
public void play(String _videoUri, int position){
Log.i(TAG,"URI is : "+Uri.parse(_videoUri).toString());
MediaController mc = new MediaController(VideoPlayer.this);
mVideoView.setMediaController(mc);
mVideoView.setVideoURI(Uri.parse(_videoUri));
mVideoView.requestFocus();
mVideoView.seekTo(position);
p_dialog.dismiss();
}
Firstly, it makes no sense to create a separate thread only to run something back on the UI thread (why do you create the thread in the first place then?).
onMenuItemClick should already be called by the UI thread (callbacks for UI elements generally do this).
What you should look at is using a MediaPlayer.OnPreparedListener with VideoView.setOnPreparedListener. This will give you an indication of when the video is ready to be played.
I did some rearrangement as per Che Jami and got it to work. Thanks
mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
p_dialog.dismiss();
mVideoView.start();
}
});
////////////////////////////////////////////////////////////////////////////////
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(final MenuItem item) {
//get current position of video to seek to
final int position = mVideoView.getCurrentPosition();
try{
if(item.getTitle().equals("Catalog")){
backButtonVideo(new View(VideoPlayer.this));
}
else if(item.getTitle().equals("Hide menu")){
popupMenu.dismiss();
mVideoView.start();
}
else{
p_dialog = ProgressDialog.show(VideoPlayer.this, "", "Loading new stream");
play(streamUrls.get(item.getItemId()),position);
}
}
catch (Exception e) {Log.e("tag", e.getMessage());}
return true;
}
});
}
public void play(String _videoUri, int position){
Log.i(TAG,"URI is : "+Uri.parse(_videoUri).toString());
MediaController mc = new MediaController(VideoPlayer.this);
mVideoView.setMediaController(mc);
mVideoView.setVideoURI(Uri.parse(_videoUri));
mVideoView.requestFocus();
mVideoView.seekTo(position);
}
I have the same problem...i've tried you solution but my progress gets blocked...everything stops...and video doesn't show up...it seems that onPrepareListener is never called up...any ideas? Also it seems that setVideoURI has never passed in code...:/
I have different versions of code...with threads, with runOnUI, with AsyncTask, without everything...nothing seems to be working fully. something is always missing.
EDIT:
I have function that I'm calling in onClickListener
Here is a code like yours without any threads:
Version 1: Video starts after few seconds, progress dialog just show for a moment when video starts. Progress isn't showed from the beginning.
public void loadService(final int mode) {
//Version 1
// Show dialog
loadService = new ProgressDialog(activity);
loadService.setTitle("Loading service");
loadService.setMessage("Please wait...");
loadService.setCancelable(false);
loadService.show();
// Hide progress dialog after 15 seconds if nothing happens
DuoTVGuiHandler.progressBarProttection(loadService, 15);
// Setup video view for playback
if (mode == STAND_ALONE) {
setupVideoView(((DuoTVGuiActivity) activity).getVideoPlayback());
}
if (mode == WIDGET_MODE) {
setupVideoView(((MainActivity) activity).getVideoViewWidgetMode());
}
}
/** Setup video view for playback */
public void setupVideoView(final VideoView videoView) {
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
loadService.dismiss();
videoView.start();
}
});
videoView.setVideoURI(Uri.parse(channels.get(index).getFilePath()));
}
Version 2 with thread and handler...progress dialog is showed...its spinning...video shows for a second...and the app crashes...WrongThread for UI exception...but when i move setVideoURI in runOnUiThread...progress just stays forever...and setOnVideoURI is never finished.
public void loadService(final int mode) {
// //////////////////////////////
// Version 2
// //////////////////////////////
// Show dialog
loadService = new ProgressDialog(activity);
loadService.setTitle("Loading service");
loadService.setMessage("Please wait...");
loadService.setCancelable(false);
loadService.show();
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
loadService.dismiss();
super.handleMessage(msg);
}
};
Thread loadVideoPath = new Thread(new Runnable() {
public void run() {
if (mode == STAND_ALONE) {
((DuoTVGuiActivity) activity)
.getVideoPlayback()
.setVideoURI(
Uri.parse(channels.get(index).getFilePath()));
}
if (mode == WIDGET_MODE) {
((MainActivity) activity)
.getVideoViewWidgetMode()
.setVideoURI(
Uri.parse(channels.get(index).getFilePath()));
}
handler.sendEmptyMessage(0);
}
});
loadVideoPath.start();
}
Hope you have some idea...I've lost few days on this...and cant see solution...for this pretty basic thing...it drives me crazy :)

Android loading animation before VideoView start

I don't find any solution to show a loading animation (or just an imageView) before a VideoView start to play : during the video is buffering.
Does anyone have a clue ?
Thanks.
Or you can just use Progress Dialog;
public class VideoEkrani extends Activity {
VideoView ekran;
String kaynakYolu = "http://commonsware.com/misc/test2.3gp";
ProgressDialog progDailog;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sayfa_video_goruntule);
ekran = (VideoView) findViewById(R.id.videoViewESPU);
ekran.setMediaController(new MediaController(this));
ekran.setVideoURI(Uri.parse(kaynakYolu));
ekran.requestFocus();
ekran.start();
progDailog = ProgressDialog.show(this, "Please wait ...", "Retrieving data ...", true);
ekran.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
progDailog.dismiss();
}
});
}
}
Finally I found the method setOnPreparedListener() on VideoView.
I added a ProgressBar inside my layout, and hide it with the OnPreparedListener
You cant detect the video buffer using OnBufferingUpdateListener on MediaPlayer. If you use VideView set that listener inside OnPreparedListener.
videoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mp.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
if(percent == 100){
//video have completed buffering
}
}
});
}
});

Categories

Resources