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();
}
});
}
Related
I am having 3 tones. I am calling playmusic() function to play 2 of these tones on imageview toggle. when i click on imageview for first time tone1 starts playing. when i click 2nd time on the same imageview tone2 starts playing, but tone1 is not stopped.
my requiremet is , when i click on imageview for -
(1st time - tone1 should start playing).
(2nd time - tone1 should stop playing and tone2 should start playing)
(3rd time - tone2 should stop playing and tone1 should start playing again)
and so on....
String file=null;
int x=0;
public void playMusic(int i) {
x=i;
if(i==1){
file = R.raw.tone1;
}else if(i==2){
file = R.raw.tone2;
}else{
file = R.raw.tone3;
}
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
AssetFileDescriptor assetFileDescriptor =
Main2Activity.this.getResources().openRawResourceFd(file);
if(assetFileDescriptor == null) return;
try {
mediaPlayer.setDataSource(
assetFileDescriptor.getFileDescriptor(),
assetFileDescriptor.getStartOffset(),
assetFileDescriptor.getLength()
);
assetFileDescriptor.close();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if(mediaPlayer != null){
mediaPlayer.release();
mediaPlayer = null;
}
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(final MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
// HelpFunctions.showLog("ERROR = " + e);
} catch (IllegalStateException e) {
// HelpFunctions.showLog("ERROR = " + e);
} catch (IOException e) {
// HelpFunctions.showLog("ERROR = " + e);
}
}
I did a small modification on your logic and added mediaplayer.reset(). Here is the solution link
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView player = findViewById(R.id.play);
player.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
playMusic(1);
}
});
mediaPlayer = new MediaPlayer();
}
int file = 0;
MediaPlayer mediaPlayer;
int x = 0;
public void playMusic(int i) {
x = x + i;
if (x == 1) {
file = R.raw.tone1;
}
else if (x == 2) {
file = R.raw.tone2;
} else {
x = 0;
file = R.raw.tone3;
}
mediaPlayer.reset();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
AssetFileDescriptor assetFileDescriptor =
MainActivity.this.getResources().openRawResourceFd(file);
if (assetFileDescriptor == null) return;
try {
mediaPlayer.setDataSource(
assetFileDescriptor.getFileDescriptor(),
assetFileDescriptor.getStartOffset(),
assetFileDescriptor.getLength()
);
assetFileDescriptor.close();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if (mediaPlayer != null) {
mediaPlayer.release();
}
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(final MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
// HelpFunctions.showLog("ERROR = " + e);
} catch (IllegalStateException e) {
// HelpFunctions.showLog("ERROR = " + e);
} catch (IOException e) {
// HelpFunctions.showLog("ERROR = " + e);
}
}
}
when i click 2nd time on the same imageview tone2 starts playing, but tone1 is not stopped.
If that's the only issue, try putting the following line before you call mediaPlayer = new MediaPlayer();:
if (mediaPlayer != null && mediaPlayer.isPlaying()) mediaPlayer.stop();
below is the code that I am using . I am using a vimeo video url it is working fine when I first load the activity but gets problem when calling the activity second time it show message Attempt to call getDuration on invalid media player.
public class VideoActivity extends Activity {
public LinearLayout main_Lay;
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";
public boolean isFullScreen = false;
private Context m_context;
public GestureDetector ggg;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.video_layout);
this.m_context = this;
main_Lay = (LinearLayout) findViewById(R.id.main_lay);
main_Lay.startAnimation(AnimationUtils.loadAnimation(this,
R.anim.slide_out_up));
surfaceViewFrame = (SurfaceView) findViewById(R.id.surfaceViewFrame);
final Button button = (Button) findViewById(R.id.full);
ggg = new GestureDetector(new OnGestureListener() {
public boolean onSingleTapUp(MotionEvent arg0) {
// TODO Auto-generated method stub
try {
if (player != null) {
if (player.isPlaying())
player.stop();
player.reset();
player.release();
if (updateTimer != null) {
updateTimer.cancel();
}
finish();
}
} catch (Exception ex) {
ex.printStackTrace();
player.reset();
player.release();
if (updateTimer != null) {
updateTimer.cancel();
}
finish();
}
return true;
}
public void onShowPress(MotionEvent arg0) {
// TODO Auto-generated method stub
}
public boolean onScroll(MotionEvent arg0, MotionEvent arg1,
float arg2, float arg3) {
// TODO Auto-generated method stub
return false;
}
public void onLongPress(MotionEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean onFling(MotionEvent arg0, MotionEvent arg1,
float arg2, float arg3) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onDown(MotionEvent arg0) {
// TODO Auto-generated method stub
return false;
}
});
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (player != null) {
if (!isFullScreen) {
isFullScreen = true;
button.setBackgroundResource(R.drawable.fullscreen_exit_alt);
// Get the width of the screen
int screenWidth = ((Activity) m_context)
.getWindowManager().getDefaultDisplay()
.getWidth();
int screenHeight = ((Activity) m_context)
.getWindowManager().getDefaultDisplay()
.getHeight();
WidthResizeAnimation zoom_out = new WidthResizeAnimation(
main_Lay, screenWidth, screenHeight, false);
zoom_out.setDuration(600);
zoom_out.setFillAfter(true);
WidthResizeAnimation zoom_outt = new WidthResizeAnimation(
surfaceViewFrame, screenWidth, screenHeight,
false);
zoom_outt.setDuration(600);
zoom_outt.setFillAfter(true);
surfaceViewFrame.startAnimation(zoom_outt);
main_Lay.startAnimation(zoom_out);
} else {
isFullScreen = false;
button.setBackgroundResource(R.drawable.fullscreen_alt);
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 = ((Activity) m_context)
.getWindowManager().getDefaultDisplay()
.getWidth();
int screenHeight = ((Activity) m_context)
.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();
android.view.ViewGroup.LayoutParams mainLayoutParam = main_Lay
.getLayoutParams();
if (videoProportion > screenProportion) {
lp.width = screenWidth;
lp.height = (int) ((float) screenWidth / videoProportion);
lp.width = (lp.width / 100) * 80;
lp.height = (lp.height / 100) * 80;
} else {
lp.width = (int) (videoProportion * (float) screenHeight);
lp.height = screenHeight;
lp.width = (lp.width / 100) * 70;
lp.height = (lp.height / 100) * 70;
}
WidthResizeAnimation zoom_in = new WidthResizeAnimation(
main_Lay, lp.width, lp.height, false);
zoom_in.setDuration(600);
zoom_in.setFillAfter(true);
// zoom_in.start();
WidthResizeAnimation zoom_inn = new WidthResizeAnimation(
surfaceViewFrame, lp.width, lp.height, false);
zoom_inn.setDuration(600);
zoom_inn.setFillAfter(true);
// zoom_in.start();
surfaceViewFrame.startAnimation(zoom_inn);
main_Lay.startAnimation(zoom_in);
}
}
}
});
final Button pause = (Button) findViewById(R.id.pause);
pause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (player != null) {
if (player.isPlaying()) {
player.pause();
pause.setBackgroundResource(R.drawable.play);
imageViewPauseIndicator.setVisibility(View.GONE);
} else {
pause.setBackgroundResource(R.drawable.pause);
player.start();
imageViewPauseIndicator.setVisibility(View.GONE);
}
}
}
});
linearLayoutMediaController = (LinearLayout) findViewById(R.id.linearLayoutMediaController);
linearLayoutMediaController.setVisibility(View.GONE);
hideMediaController = AnimationUtils.loadAnimation(m_context,
R.anim.disapearing);
hideMediaController.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation arg0) {
// TODO Auto-generated
// method stub
linearLayoutMediaController.setVisibility(View.GONE);
}
#Override
public void onAnimationRepeat(Animation arg0) {
// TODO Auto-generated
// method stub
}
#Override
public void onAnimationEnd(Animation arg0) {
// TODO Auto-generated
// method stub
}
});
imageViewPauseIndicator = (ImageView) findViewById(R.id.imageViewPauseIndicator);
imageViewPauseIndicator.setVisibility(View.GONE);
if (player != null) {
if (!player.isPlaying()) {
imageViewPauseIndicator.setVisibility(View.GONE);
}
}
textViewPlayed = (TextView) findViewById(R.id.textViewPlayed);
textViewLength = (TextView) findViewById(R.id.textViewLength);
surfaceViewFrame.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated
// method stub
if (arg0.getId() == R.id.surfaceViewFrame) {
if (linearLayoutMediaController.getVisibility() == View.GONE) {
linearLayoutMediaController.setVisibility(View.VISIBLE);
hideMediaController();
}
}
}
});
surfaceViewFrame.setClickable(false);
seekBarProgress = (SeekBar) findViewById(R.id.seekBarProgress);
seekBarProgress
.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated
// method stub
if (player.isPlaying()) {
progressBarWait.setVisibility(View.VISIBLE);
player.seekTo(arg0.getProgress() * 1000);
Log.i(TAG,
"========== SeekTo : " + arg0.getProgress());
}
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated
// method stub
}
#Override
public void onProgressChanged(SeekBar seekBar,
int progress, boolean fromUser) {
Log.i(TAG, "========== onProgressChanged : " + progress
+ " from user: " + fromUser);
if (!fromUser) {
textViewPlayed
.setText(durationInSecondsToString(progress));
}
}
});
seekBarProgress.setProgress(0);
progressBarWait = (ProgressBar) findViewById(R.id.progressBarWait);
holder = surfaceViewFrame.getHolder();
holder.addCallback(new Callback() {
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
player.setDisplay(holder);
playVideo();
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
player = new MediaPlayer();
player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer arg0) {
// TODO Auto-generated method stub
Log.i(TAG, "========== onPrepared ===========");
try {
int duration = player.getDuration() / 1000; // duration
// in
// seconds
seekBarProgress.setMax(duration);
textViewLength.setText(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);
player.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
// Get the width of the screen
int screenWidth = ((Activity) m_context).getWindowManager()
.getDefaultDisplay().getWidth();
int screenHeight = ((Activity) m_context)
.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();
android.view.ViewGroup.LayoutParams mainLayoutParam = main_Lay
.getLayoutParams();
if (videoProportion > screenProportion) {
lp.width = screenWidth;
lp.height = (int) ((float) screenWidth / videoProportion);
lp.width = (lp.width / 100) * 80;
lp.height = (lp.height / 100) * 80;
} else {
lp.width = (int) (videoProportion * (float) screenHeight);
lp.height = screenHeight;
lp.width = (lp.width / 100) * 90;
lp.height = (lp.height / 100) * 90;
}
// Commit the layout parameters
surfaceViewFrame.setLayoutParams(lp);
RelativeLayout.LayoutParams rr = new RelativeLayout.LayoutParams(
lp.width, lp.height);
rr.addRule(RelativeLayout.CENTER_IN_PARENT);
main_Lay.setLayoutParams(rr);
// Start video
if (!player.isPlaying()) {
player.start();
updateMediaProgress();
linearLayoutMediaController.setVisibility(View.VISIBLE);
hideMediaController();
}
surfaceViewFrame.setClickable(true);
} catch (Exception ex) {
player.release();
finish();
ex.printStackTrace();
}
;
}
});
player.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
if (arg0.isPlaying()) {
arg0.stop();
}
arg0.release();
finish();
Log.e("Lrapp", "Error code" + arg1);
return true;
}
});
player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
arg0.stop();
arg0.release();
if (updateTimer != null) {
updateTimer.cancel();
}
finish();
}
});
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
#Override
public void onBufferingUpdate(MediaPlayer arg0, int arg1) {
// TODO Auto-generated method stub
int progress = (int) ((float) arg0.getDuration() * ((float) arg1 / (float) 100));
seekBarProgress.setSecondaryProgress(progress / 1000);
}
});
player.setOnSeekCompleteListener(new OnSeekCompleteListener() {
#Override
public void onSeekComplete(MediaPlayer arg0) {
// TODO Auto-generated method stub
progressBarWait.setVisibility(View.GONE);
}
});
player.setScreenOnWhilePlaying(true);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
return ggg.onTouchEvent(event);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
try {
if (player != null) {
if (player.isPlaying())
player.stop();
player.release();
if (updateTimer != null) {
updateTimer.cancel();
}
finish();
}
} catch (Exception ex) {
ex.printStackTrace();
player.release();
if (updateTimer != null) {
updateTimer.cancel();
}
finish();
}
}
private void playVideo() {
new Thread(new Runnable() {
public void run() {
try {
player.setDataSource("video url");
player.prepareAsync();
} catch (IllegalArgumentException e) {
showToast("Error while playing video. Please, check your network connection.");
Log.i(TAG,
"========== IllegalArgumentException ===========");
e.printStackTrace();
if (player.isPlaying())
player.stop();
player.release();
player = null;
if (updateTimer != null) {
updateTimer.cancel();
}
finish();
} catch (IllegalStateException e) {
showToast("Error while playing video. Please, check your network connection.");
Log.i(TAG, "========== IllegalStateException ===========");
e.printStackTrace();
if (player.isPlaying())
player.stop();
player.release();
player = null;
if (updateTimer != null) {
updateTimer.cancel();
}
finish();
} catch (IOException e) {
showToast("Error while playing video. Please, check your network connection.");
Log.i(TAG, "========== IOException ===========");
e.printStackTrace();
if (player.isPlaying())
player.stop();
player.release();
player = null;
if (updateTimer != null) {
updateTimer.cancel();
}
finish();
}
}
}).start();
}
private void showToast(final String string) {
((Activity) m_context).runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(m_context, string, Toast.LENGTH_LONG).show();
;
}
});
}
private void hideMediaController() {
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(5000);
((Activity) m_context).runOnUiThread(new Runnable() {
public void run() {
linearLayoutMediaController
.startAnimation(hideMediaController);
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
private void updateMediaProgress() {
updateTimer = new Timer("progress Updater");
updateTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
((Activity) m_context).runOnUiThread(new Runnable() {
public void run() {
try {
seekBarProgress.setProgress(player
.getCurrentPosition() / 1000);
} catch (Exception ex) {
ex.printStackTrace();
player.release();
}
}
});
}
}, 0, 1000);
}
public static String durationInSecondsToString(int sec) {
int hours = sec / 3600;
int minutes = (sec / 60) - (hours * 60);
int seconds = sec - (hours * 3600) - (minutes * 60);
String formatted = String.format("%d:%02d:%02d", hours, minutes,
seconds);
return formatted;
}
}
After you open the activity the second time, the surface callback is called -> playVideo() -> player doesn't init well.
The solution may be:
Insert this into the playVideo() method:
if (player != null)
{
player.reset();
} else
{
player = new MediaPlayer();
}
//init
I am doing to run wowza sample link in android. Wowza sample link is
here. but it is not working in android.
My code is here.
HelloAndroidActivity(MainActivity)
public class HelloAndroidActivity extends Activity implements OnClickListener {
private static String TAG = "androidEx2";
private Button buttonVideoSample;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate");
setContentView(R.layout.main);
buttonVideoSample = (Button) findViewById(R.id.buttonVideoSample);
buttonVideoSample.setOnClickListener(this);
}
public void onClick(View v) {
if (v.getId() == R.id.buttonVideoSample) {
String video_uri = "rtsp://184.72.239.149/vod/mp4:BigBuckBunny_115k.mov";
Intent intent = new Intent(this, VideoSample.class);
intent.putExtra("video_path", video_uri);
startActivity(intent);
}
}
}
Utils.java
public class Utils {
public static String durationInSecondsToString(int sec){
int hours = sec / 3600;
int minutes = (sec / 60) - (hours * 60);
int seconds = sec - (hours * 3600) - (minutes * 60) ;
String formatted = String.format("%d:%02d:%02d", hours, minutes, seconds);
return formatted;
}
}
VideoSampleActivity
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 = "log_tag";
#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);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
player = new MediaPlayer();
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnBufferingUpdateListener(this);
player.setOnSeekCompleteListener(this);
player.setScreenOnWhilePlaying(true);
player.setDisplay(holder);
}
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(VideoSample.this, Uri.parse(extras.getString("video_path")));
//player.setDataSource(extras.getString("video_path"));
//player.start();
player.prepare();
} catch (IllegalArgumentException e) {
showToast("Error while playing video");
Log.i(TAG, e.getMessage());
e.printStackTrace();
} catch (IllegalStateException e) {
showToast("Error while playing video");
Log.i(TAG, e.getMessage());
e.printStackTrace();
} catch (IOException e) {
showToast("Error while playing video. Please, check your network connection.");
Log.i(TAG, e.getMessage());
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) {
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) {
}
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) {
}
public void surfaceCreated(SurfaceHolder holder) {
playVideo();
}
public void surfaceDestroyed(SurfaceHolder holder) {
}
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();
}
/**
* 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) {
}
public void onAnimationRepeat(Animation animation) {
}
public void onAnimationStart(Animation animation) {
linearLayoutMediaController.setVisibility(View.GONE);
}
}
I don't think there would be room in comments...
The view:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/hls_frame"
android:background="#000000"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<VideoView
android:id="#+id/video_player"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_gravity="center"
/>
<include layout="#layout/player_bar" />
</FrameLayout>
In the following code, the activity is passed in to a separate class (this would normally happen in the activity itself, but I need to support multiple players for older devices). The method of interest:
public void loadPlayer() {
_activity.setContentView(R.layout.hls_video_view);
if (_activity.url == null) {
Development.ExceptionMsg("Video Url is Null!");
return;
}
VideoView view = (VideoView) _activity.findViewById(R.id.video_player);
if (!_activity.isLive) {
//MediaController for vod only
MediaController controller = new MediaController(_activity);
controller.setAnchorView(view);
view.setMediaController(controller);
}
_activity.LogStreamStart();
_activity.HideBuffering();
view.setOnCompletionListener(this);
view.setOnPreparedListener(this);
view.setOnErrorListener(this);
//this is important, and should perhaps be part of the interface
view.setOnTouchListener(_activity);
view.setVideoURI(Uri.parse(_activity.url));
view.requestFocus();
view.start();
}
I want to play a live HTTP stream in my Android app, so I installed the Windows Media Encoder 9 on another PC on the same LAN, and used it to create a live HTTP audio stream.
The live HTTP stream is okay: I tested it, and it can be played by Windows Media Player or VLC on a PC, and can be played by VLC for Android on my mobile.
So, in my Android app, I wrote this code:
private MediaPlayer player = null;
#Override
public void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
//.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPlay = (Button)findViewById(R.id.play);
address = (TextView)findViewById(R.id.address);
btnPlay.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
play();
}
});
}
private void play()
{
String serverIp;
serverIp = address.getText().toString(); // get the uri address, for example http://xxx.xxx.xxx.xxx:2340
if (player == null)
{
player = new MediaPlayer();
}
else
{
player.stop();
player.reset();
}
try {
Log.v("", "Init a new MediaPlayer");
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
Log.v("", "Set the stream type to STREAM_MUSIC");
player.setDataSource(this, Uri.parse(serverIp));
Log.v("", "Set the source is " + serverIp);
player.setOnBufferingUpdateListener(this);
player.setOnPreparedListener(this);
player.setOnErrorListener(this);
player.prepareAsync();
Log.v("", "After prepareAsync");
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
Log.v("IllegalArgumentException", e.toString());
} catch (SecurityException e) {
// TODO Auto-generated catch block
Log.v("SecurityException", e.toString());
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
Log.v("IllegalStateException", e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.v("IOException", e.toString());
} catch (Exception e) {
Log.v("Exception",e.toString());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
try {
Log.v("onPrepared", "After prepareAsync");
mp.start();
}
catch (Exception e) {
Log.v("play", e.toString());
}
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
// TODO Auto-generated method stub
Log.v("onBufferingUpdate", "Buffering Update");
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
Log.v("MediaPlayer onError", "what=" + what + " extra=" + extra);
return true;
}
But it didn’t work. When I click the play button, nothing happens. But if I input some other URL I found on the internet (for example, http://www.example.com/song.mp3), it works.
So can anyone help me? The Log info is below. My mobile is HTC s710e, and my Android version is 4.0.4.
11-20 22:28:14.137: V/(580): Init a new MediaPlayer
11-20 22:28:14.137: V/(580): Set the stream type tp STREAM_MUSIC
11-20 22:28:14.147: D/MediaPlayer(580): Couldn't open file on client side, trying server side
11-20 22:28:14.178: E/Trace(39): error opening trace file: No such file or directory (2)
11-20 22:28:14.178: V/(580): After prepareAsync
11-20 22:28:14.297: V/ChromiumHTTPDataSource(39): connect on behalf of uid 10044
11-20 22:28:14.339: I/qtaguid(39): Tagging socket 27 with tag 3f500000000(1013) for uid 10044 failed errno=-2
11-20 22:28:14.629: I/ChromiumHTTPDataSourceSupport(39): Server responded with http status 400
11-20 22:28:14.648: I/qtaguid(39): Untagging socket 27 failed errno=-2
11-20 22:28:14.657: I/AwesomePlayer(39): mConnectingDataSource->connect() returned -1004
11-20 22:28:14.657: E/MediaPlayer(580): error (1, -1004)
11-20 22:28:14.667: E/MediaPlayer(580): Error (1,-1004)
11-20 22:28:14.667: V/MediaPlayer onError(580): what=1 extra=-1004
you can play HLS on android 3.0and 3.0 + version, older versions doesnt support HLS. This code below, can work on 3.0 + version. To play video all android version you have to use rtsp streaming or http prograssive download.
Player class
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class VideoPlayerActivity extends Activity implements
OnBufferingUpdateListener, OnCompletionListener,
OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback {
private static final String TAG = "MediaPlayerDemo";
private int mVideoWidth;
private int mVideoHeight;
private MediaPlayer mMediaPlayer;
private SurfaceView mPreview;
private SurfaceHolder holder;
private String path;
private Bundle extras;
private static final String MEDIA = "media";
private static final int STREAM_VIDEO = 5;
private boolean mIsVideoSizeKnown = false;
private boolean mIsVideoReadyToBePlayed = false;
/**
*
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mPreview = (SurfaceView) findViewById(R.id.VideoView);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
extras = getIntent().getExtras();
}
private void playVideo(Integer Media) {
doCleanUp();
try {
path = "http://www.pocketjourney.com/downloads/pj/video/famous.3gp";
// Create a new media player and set the listeners
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(path);
mMediaPlayer.setDisplay(holder);
mMediaPlayer.prepare();
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
//mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (Exception e) {
Log.e(TAG, "error: " + e.getMessage(), e);
}
}
public void onBufferingUpdate(MediaPlayer arg0, int percent) {
Log.d(TAG, "onBufferingUpdate percent:" + percent);
}
public void onCompletion(MediaPlayer arg0) {
Log.d(TAG, "onCompletion called");
}
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;
}
mIsVideoSizeKnown = true;
mVideoWidth = width;
mVideoHeight = height;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void onPrepared(MediaPlayer mediaplayer) {
Log.d(TAG, "onPrepared called");
mIsVideoReadyToBePlayed = true;
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(STREAM_VIDEO);
}
#Override
protected void onPause() {
super.onPause();
releaseMediaPlayer();
doCleanUp();
}
#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;
mIsVideoSizeKnown = false;
}
private void startVideoPlayback() {
Log.v(TAG, "startVideoPlayback");
holder.setFixedSize(mVideoWidth, mVideoHeight);
mMediaPlayer.start();
}
}
Main XML
<VideoView
android:id="#+id/VideoView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_weight="1"/>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:layout_weight="1" android:background="#aaaaaa">
</LinearLayout>
</LinearLayout>
And you have to add to your manifest internet permission
uses-permission android:name="android.permission.INTERNET" />
I have a problem of that how to setup seekbar to work correctly when I setProgress upon click. Progress is jumping to the beginning/middle/end depends on where I click on it. How is it possible to solve?
That my attemps:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
videoPath = getIntent().getExtras().getString("videoPath");
videoView = (VideoView) findViewById(R.id.vvPlayer);
seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(this);
....
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
seekBar.setMax(mp.getDuration());
System.out.println("curpos" + mp.getCurrentPosition());
new Thread(new Runnable() {
public void run() {
try {
while (mPlayer != null && mPlayer.getCurrentPosition() < mPlayer.getDuration()) {
seekBar.setProgress(mPlayer.getCurrentPosition());
Message msg = new Message();
int millis = mPlayer.getCurrentPosition();
msg.obj = millis / 1000;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("interrupt exeption" + e);
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("my Exception" + e);
}
}
}).start();
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
Log.e("onProgressChanged: ", Integer.toString(progress));
mPlayer.seekTo(progress);
}
}
Full Code:
public class VideoPlayerActivity extends Activity implements Callback, OnSeekBarChangeListener, OnTouchListener, OnErrorListener, OnCompletionListener, OnPreparedListener {
MediaPlayer mPlayer;
AssetFileDescriptor afd;
VideoView videoView;
SurfaceHolder holder;
MediaController mController;
String videoPath;
SeekBar seekBar;
ImageButton mPlay, mStop, mPause;
TextView mCurDuration, mDuration;
int position = 0;
Handler handler = new Handler();
Runnable r;
boolean controlsVisibility = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
mDuration = (TextView) findViewById(R.id.tvDuration);
mCurDuration = (TextView) findViewById(R.id.tvCurDuration);
videoPath = getIntent().getExtras().getString("videoPath");
videoView = (VideoView) findViewById(R.id.vvPlayer);
seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(this);
seekBar.setFocusable(false);
videoView.setOnTouchListener(this);
mPlay = (ImageButton) findViewById(R.id.play);
mPause = (ImageButton) findViewById(R.id.pause);
mStop = (ImageButton) findViewById(R.id.stop);
mController = new MediaController(this);
videoView.setMediaController(mController);
holder = videoView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mPlay.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Log.e("Play:", " is Pressed!");
if (mPlayer == null)
playVideo();
mPlayer.start();
}
});
mPause.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Log.e("Pause:", " is Pressed!");
if (mPlayer != null) {
handler.removeCallbacks(r);
controlsVisibility=true;
AutoHideControls();
Log.e("mPlayer status: ", "Not Null");
if (mPlayer.isPlaying())
Log.e("mPlayer status: ", "Not Null");
mPlayer.pause();
}
}
});
mStop.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Log.e("Stop:", " is Pressed!");
if (mPlayer != null) {
handler.removeCallbacks(r);
controlsVisibility=true;
AutoHideControls();
seekBar.setProgress(0);
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
}
});
}
private void playVideo() {
try {
if (afd != null && mPlayer != null) {
mPlayer.start();
return;
}
Log.e("VideoPath:", videoPath);
if (videoPath != "") {
afd = getAssets().openFd(videoPath);
// "videos/start.mp4"
mPlayer = new MediaPlayer();
mPlayer.setOnErrorListener(this);
mPlayer.setOnCompletionListener(this);
mPlayer.setOnPreparedListener(this);
mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mPlayer.setScreenOnWhilePlaying(true);
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDisplay(holder);
mPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mPlayer.prepare();
mPlayer.start();
handler.removeCallbacks(r);
controlsVisibility=true;
AutoHideControls();
}
} 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 surfaceCreated(SurfaceHolder holder) {
runOnUiThread(new Runnable() {
public void run() {
playVideo();
}
});
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.e("Debug:", "onError---> what:" + what + " extra:" + extra);
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
return true;
}
#Override
public void onCompletion(MediaPlayer mp) {
mPlayer.release();
finish();
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
}
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (controlsVisibility) {
controlsVisibility = false;
mPlay.setVisibility(View.GONE);
mPause.setVisibility(View.GONE);
mStop.setVisibility(View.GONE);
seekBar.setVisibility(View.GONE);
handler.removeCallbacks(r);
} else {
controlsVisibility = true;
mPlay.setVisibility(View.VISIBLE);
mPause.setVisibility(View.VISIBLE);
mStop.setVisibility(View.VISIBLE);
seekBar.setVisibility(View.VISIBLE);
AutoHideControls();
}
return false;
}
public void AutoHideControls() {
r = new Runnable() {
public void run() {
controlsVisibility = false;
mPlay.setVisibility(View.GONE);
mPause.setVisibility(View.GONE);
mStop.setVisibility(View.GONE);
seekBar.setVisibility(View.GONE);
}
};
handler.removeCallbacks(r);
handler.postDelayed(r, 4000);
}
#Override
public void onPrepared(MediaPlayer mp) {
seekBar.setMax(mp.getDuration());
new Thread(new Runnable() {
public void run() {
int currentPosition = 0;
int total = mPlayer.getDuration();
seekBar.setMax(total);
while (mPlayer != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mPlayer.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
}).start();
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
Log.e("onProgressChanged: ", Integer.toString(progress));
mPlayer.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
The same but throughtout AsyncTask (but the same result - still jumping):
#Override
public void onPrepared(MediaPlayer mp) {
seekBar.setMax(mp.getDuration());
new Async().execute();
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
Log.e("onProgressChanged: ", Integer.toString(progress));
mPlayer.seekTo(progress);
seekBar.setProgress(progress);
Log.e("SeekedProgressTime: ", Integer.toString(mPlayer.getCurrentPosition()));
Log.e("SeekedProgressTime: ", Integer.toString(seekBar.getProgress()));
}
}
class Async extends AsyncTask<Void, Integer, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
int currentPosition = 0;
int total = mPlayer.getDuration();
seekBar.setMax(total);
while (mPlayer != null && currentPosition < total) {
Log.e("Current mPlayer time in Thread: ", Integer.toString(mPlayer.getCurrentPosition()));
Log.e("Current seekBar time in Thread: ", Integer.toString(seekBar.getProgress()));
try {
Thread.sleep(1000);
currentPosition = mPlayer.getCurrentPosition();
} catch (InterruptedException e) {
} catch (Exception e) {
}
seekBar.setProgress(currentPosition);
}
return null;
}
}
Maybe, I did something wrong inside the AsyncTask, I cannot understand what is the problem with this seekBar. Check what real position it takes when you click somewhere on the seekbar, everything correct but in one moment its position value overrides somehow.