How to Record Streaming Video? - android

I am able to play a Streaming video with http server connection in a SurfaceView. And I was creating ContextMenu for recording the video by adding menu items StartRecording and StopRecording. But am able record a Camera Video by calling mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
Here I want to set Video Source as Streaming Video Source. Is there any possibility for doing this?
But I want to record the Streaming Video while it is playing. Can you please tell me how to do record while it is playing?
Will you please provide any sample code for this problem?
My sample code shown below:
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="#+id/frameLayoutRoot">
<SurfaceView android:id="#+id/surfaceViewFrame" android:layout_gravity="center" android:layout_height="wrap_content" android:layout_width="wrap_content"></SurfaceView>
<LinearLayout android:layout_width="fill_parent" android:id="#+id/linearLayoutMediaController" android:layout_height="wrap_content" android:paddingBottom="5dp"
android:paddingTop="5dp" android:layout_gravity="bottom" android:gravity="center_vertical" android:background="#color/media_controller_bg_color">
<TextView android:layout_width="wrap_content" android:id="#+id/textViewPlayed" android:layout_marginLeft="5dp" android:layout_marginRight="5dp"
android:textColor="#color/media_controller_text_color" android:textStyle="bold" android:text="0:00:00" android:padding="0dp" android:textSize="13sp" android:gravity="center"
android:layout_height="wrap_content"></TextView>
<SeekBar android:id="#+id/seekBarProgress" android:layout_weight="1" style="#style/MyCustomProgressStyle" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:progress="50"></SeekBar>
<TextView android:layout_width="wrap_content" android:id="#+id/textViewLength" android:layout_marginLeft="5dp" android:layout_marginRight="5dp"
android:textColor="#color/media_controller_text_color" android:textStyle="bold" android:text="0:00:00" android:textSize="13sp" android:padding="0dp" android:gravity="center"
android:layout_height="wrap_content"></TextView>
</LinearLayout>
<ProgressBar style="?android:attr/progressBarStyleLarge" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center"
android:id="#+id/progressBarWait"></ProgressBar>
<ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/imageViewPauseIndicator" android:layout_gravity="center"
android:src="#drawable/pause_button"></ImageView>
</FrameLayout>
MediaPlayerDemo.java:
public class MediaPlayerDemo_Video extends Activity implements
OnBufferingUpdateListener, OnCompletionListener, OnPreparedListener, OnClickListener, OnSeekCompleteListener,
Callback, OnSeekBarChangeListener, AnimationListener {
private String path2 = "http://commonsware.com/misc/test2.3gp";
private String path = "";
private static final String TAG = "MediaPlayerDemo";
private MediaRecorder mediaRecorder;
private MediaPlayer mMediaPlayer;
private SurfaceView surfaceViewFrame;
private SurfaceHolder surfaceHolder;
// private String path;
private Bundle extras;
private Animation hideMediaController;
private LinearLayout linearLayoutMediaController;
private SeekBar seekBarProgress;
private TextView textViewPlayed;
private TextView textViewLength;
private ProgressBar progressBarWait;
private ImageView imageViewPauseIndicator;
private Timer updateTimer;
AudioManager volume;
int keyCode = 0;
KeyEvent keyEvent;
private MediaRecorder mVideoRecorder = null;
private Camera mCamera;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.mediaplayer_2);
linearLayoutMediaController = (LinearLayout) findViewById(R.id.linearLayoutMediaController);
linearLayoutMediaController.setVisibility(View.GONE);
hideMediaController = AnimationUtils.loadAnimation(MediaPlayerDemo_Video.this, R.anim.disapearing);
hideMediaController.setAnimationListener(this);
imageViewPauseIndicator = (ImageView) findViewById(R.id.imageViewPauseIndicator);
imageViewPauseIndicator.setVisibility(View.GONE);
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);
volume = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int maxVolume = volume.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int curVolume = volume.getStreamVolume(AudioManager.STREAM_MUSIC);
seekBarProgress.setMax(maxVolume);
seekBarProgress.setProgress(curVolume);
surfaceHolder = surfaceViewFrame.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnSeekCompleteListener(this);
mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
if (mMediaPlayer != null) {
if (!mMediaPlayer.isPlaying()) {
imageViewPauseIndicator.setVisibility(View.VISIBLE);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, "StartRecording");
menu.add(0, 0, 0, "StopRecording");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
if (mediaRecorder == null)
mediaRecorder = new MediaRecorder(); // Works well
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
mediaRecorder.setOutputFile("/sdcard/DCIM/Camera/StreamLive.3gp");
mediaRecorder.setMaxDuration(-1);
try {
mediaRecorder.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case 1:
mediaRecorder.stop();
mediaRecorder.release();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
private void playVideo() {
try {
mMediaPlayer.setDataSource(path);
} 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();
}
mMediaPlayer.setDisplay(surfaceHolder);
try {
mMediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
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();
}
public void onPrepared(MediaPlayer mediaplayer) {
Log.i(TAG, "========== onPrepared ===========");
int duration = mediaplayer.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 = mMediaPlayer.getVideoWidth();
int videoHeight = mMediaPlayer.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 (!mMediaPlayer.isPlaying()) {
mMediaPlayer.start();
updateMediaProgress();
linearLayoutMediaController.setVisibility(View.VISIBLE);
hideMediaController();
}
surfaceViewFrame.setClickable(true);
}
public void onCompletion(MediaPlayer mp) {
Log.d(TAG, "onCompletion called");
mp.stop();
if (updateTimer != null) {
updateTimer.cancel();
}
// mp.seekTo(0);
// finish();
}
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.d(TAG, "onBufferingUpdate percent:" + percent);
int progress = (int) ((float) mp.getDuration() * ((float) percent / (float) 100));
seekBarProgress.setSecondaryProgress(progress / 1000);
}
}

The problem is like what I faced with record streaming audio on android..
You can try write video header(depends on your video format) to stream and append data when buffer updated..flush stream to wherever you want to..
Check out how RehearsalAudioRecorder works.

Related

Android Videoview Issue

I want to run video in full screen in portrait mode. I m able to run video in full screen but my video is stretching. I am using videoview. And tried TextureView/SurfaceView but no luck.
I am unable to maintain the aspect ratio of video.
Below is my code:
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceHolder = binding.video.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mediaPlayer = new MediaPlayer();
if(mediaPlayer.isPlaying()){
mediaPlayer.reset();
}
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(getApplicationContext(), mUri);
mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// surfaceHolder.setFixedSize(surfaceView_Width,surfaceView_Height);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.setLooping(true);
/*
* Handle aspect ratio
*/
int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
int screenHeight = getWindowManager().getDefaultDisplay().getHeight();
float screenProportion = (float) screenWidth / (float) screenHeight;
int surfaceView_Width = binding.video.getWidth();
int surfaceView_Height = binding.video.getHeight();
float video_Width = mediaPlayer.getVideoWidth();
float video_Height = mediaPlayer.getVideoHeight();
float videoProportion = (float) video_Width / (float) video_Height;
LayoutParams layoutParams = binding.video.getLayoutParams();
if (videoProportion > screenProportion) {
layoutParams.width = screenWidth;
layoutParams.height = (int) ((float) screenWidth / videoProportion);
} else {
layoutParams.width = (int) (videoProportion * (float) screenHeight);
layoutParams.height = screenHeight;
}
binding.video.setLayoutParams(layoutParams);
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
mediaPlayer.setDisplay(surfaceHolder);
}
Please help me with this. Thanks in advance.

surfaceview playing video as stretched view

I am using the mediaplayer.xml to play the video file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/MainView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#4d4d4d"
android:gravity="center"
android:keepScreenOn="true"
android:orientation="vertical" >
<SurfaceView
android:id="#+id/surfaceView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
</LinearLayout>
The following MediaPlayerActivity class using SurfaceView and MediaPlayer
While playing video in portrait mode it seems that the video stretched one. I want to play the video vertically center and should not occupy the full screen and then in landscape mode should play in full screen mode.
public class MediaPlayerActivity extends Activity implements OnCompletionListener,
OnErrorListener, OnInfoListener, OnBufferingUpdateListener,
OnPreparedListener, OnSeekCompleteListener, SurfaceHolder.Callback,
MediaController.MediaPlayerControl {
private MediaController controller;
Display currentDisplay;
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
private MediaPlayer mediaPlayer;
int videoWidth = 0;
int videoHeight = 0;
boolean readyToPlay = false;
private String streamingVideoUrl;
private ProgressDialog dialog;
public final String TAG = "VIDEO_PLAYER";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG,"Media player activity called ");
setContentView(R.layout.mediaplayer);
if(getIntent() != null ){
streamingVideoUrl = getIntent().getStringExtra("stream_url");
}
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
surfaceView.setOnClickListener(surViewClickListener);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
/*setVideoSize();*/
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnInfoListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//Log.d(TAG,"Returned by getDatasource :"+getDataSource(streamingVideoUrl));
mediaPlayer.setDataSource(streamingVideoUrl);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
currentDisplay = getWindowManager().getDefaultDisplay();
controller = new MediaController(this);
dialog = new ProgressDialog(this);
//dialog.setMessage("Preparing File to Streaming");
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCanceledOnTouchOutside(false);
if(this!= null && !this.isFinishing()){
dialog.show();
}
handler.postDelayed(r, 100);
}
/*private void setVideoSize() {
try {
// // Get the dimensions of the video
int videoWidth = mediaPlayer.getVideoWidth();
int videoHeight = mediaPlayer.getVideoHeight();
float videoProportion = (float) videoWidth / (float) videoHeight;
// Get the width of the screen
int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
int screenHeight = getWindowManager().getDefaultDisplay().getHeight();
float screenProportion = (float) screenWidth / (float) screenHeight;
// Get the SurfaceView layout parameters
android.view.ViewGroup.LayoutParams lp = surfaceView.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
surfaceView.setLayoutParams(lp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
/*//coded by Karthikeyan V
//converting url to byte
private String getDataSource(String path) throws IOException {
Log.d(TAG,"getDataSource called");
if (!URLUtil.isNetworkUrl(path)) {
return path;
} else {
URL url = new URL(path);
URLConnection cn = url.openConnection();
cn.connect();
InputStream stream = cn.getInputStream();
if (stream == null)
throw new RuntimeException("stream is null");
File temp = File.createTempFile("mediaplayertmp", "dat");
temp.deleteOnExit();
String tempPath = temp.getAbsolutePath();
FileOutputStream out = new FileOutputStream(temp);
byte buf[] = new byte[128];
do {
int numread = stream.read(buf);
if (numread <= 0)
break;
out.write(buf, 0, numread);
} while (true);
try {
stream.close();
} catch (IOException ex) {
Log.e(TAG, "error: " + ex.getMessage(), ex);
}
Log.d(TAG,"temp path :"+tempPath);
return tempPath;
}
}*/
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public int getCurrentPosition() {
if(mediaPlayer !=null)
return mediaPlayer.getCurrentPosition();
else
return 0;
}
#Override
public int getDuration() {
return mediaPlayer.getDuration();
}
#Override
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
#Override
public void pause() {
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
}
}
#Override
public void seekTo(int pos) {
mediaPlayer.seekTo(pos);
}
#Override
public void start() {
mediaPlayer.start();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
if(Constants.DEBUG)
Log.v(TAG, "Media Flow surfaceChanged Called");
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if(Constants.DEBUG)
Log.v(TAG, "Media Flow surfaceCreated Called");
mediaPlayer.setDisplay(holder);
try {
mediaPlayer.prepareAsync();
} catch (IllegalStateException e) {
if(Constants.DEBUG)
Log.v(TAG, "Media Flow IllegalStateException " + e.getMessage());
finish();
}
if(Constants.DEBUG)
Log.d(TAG, "Media Flow MediaPlayer Preparing");
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if(Constants.DEBUG)
Log.v(TAG, "Media Flow surfaceDestroyed Called");
}
#Override
public void onSeekComplete(MediaPlayer mp) {
if(Constants.DEBUG)
Log.v(TAG, "Media Flow onSeekComplete Called");
}
#Override
public void onPrepared(MediaPlayer mp) {
if(Constants.DEBUG)
Log.v(TAG, "Media Flow onPrepared Called");
// dismissProgressLoading();
controller.setMediaPlayer(this);
controller.setAnchorView(this.findViewById(R.id.MainView));
controller.setEnabled(true);
controller.show();
mp.start();
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
if(Constants.DEBUG)
Log.v(TAG, "Media Flow MediaPlayer Buffering: " + percent + "%");
dismissProgressLoading();
}
#Override
public boolean onInfo(MediaPlayer mp, int whatInfo, int extra) {
//
dismissProgressLoading();
if(Constants.DEBUG)
{
if (whatInfo == MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING) {
if(Constants.DEBUG)
Log.v(TAG, "Media Flow Media Info, Media Info Bad Interleaving " + extra);
} else if (whatInfo == MediaPlayer.MEDIA_INFO_NOT_SEEKABLE) {
if(Constants.DEBUG)
Log.v(TAG, "Media Flow Media Info, Media Info Not Seekable " + extra);
} else if (whatInfo == MediaPlayer.MEDIA_INFO_UNKNOWN) {
Log.v(TAG, "Media Flow Media Info, Media Info Unknown " + extra);
} else if (whatInfo == MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING) {
Log.v(TAG, "Media Flow MediaInfo, Media Info Video Track Lagging " + extra);
} else if (whatInfo == MediaPlayer.MEDIA_INFO_METADATA_UPDATE) {
Log.v(TAG, "Media Flow MediaInfo, Media Info Metadata Update " + extra);
}
}
return false;
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
dismissProgressLoading();
StringBuilder sb = new StringBuilder();
sb.append("Media Player Error: ");
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Media Error Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
}
//sb.append(" (" + what + ") ");
sb.append(extra);
showErrorDialog("Cannot play video", sb.toString());
return true;
}
void dismissProgressLoading() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
public void onCompletion(MediaPlayer mp) {
if(Constants.DEBUG)
Log.v(TAG, "Media Flow onCompletion Called");
dismissProgressLoading();
onBackPressed();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
final Runnable r = new Runnable() {
public void run() {
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()
&& mediaPlayer.getCurrentPosition() > 0) {
if(Constants.DEBUG)
Log.d(TAG, "isPlaying : " + mediaPlayer.isPlaying());
if(Constants.DEBUG)
Log.d(TAG,
"currentPosition : "
+ mediaPlayer.getCurrentPosition());
handler.sendEmptyMessage(0);
} else {
handler.postDelayed(this, 100);
}
}
}
};
Handler handler = new Handler() {
public void handleMessage(Message msg) {
dismissProgressLoading();
}
};
#Override
protected void onResume() {
if(Constants.SHOULD_FINISH_APPLICATION)
finish();
super.onResume();
}
#Override
protected void onRestart() {
super.onRestart();
}
protected void onPause() {
super.onPause();
pause();
}
#Override
protected void onDestroy() {
super.onDestroy();
dismissProgressLoading();
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
if(controller !=null)
{
controller.hide();
}
}
OnClickListener surViewClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (controller != null) {
if (controller.isShowing()) {
controller.hide();
} else {
controller.show();
}
}
}
};
#SuppressWarnings("deprecation")
void showErrorDialog(String title, String message) {
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting Icon to Dialog
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
dialog.dismiss();
finish();
}
});
// Showing Alert Message
if(this!= null && !this.isFinishing()){
alertDialog.show();
}
}
}
handleAspectRatio() {
int surfaceView_Width = surfaceView.getWidth();
int surfaceView_Height = surfaceView.getHeight();
float video_Width = mediaPlayer.getVideoWidth();
float video_Height = mediaPlayer.getVideoHeight();
float ratio_width = surfaceView_Width/video_Width;
float ratio_height = surfaceView_Height/video_Height;
float aspectratio = video_Width/video_Height;
LayoutParams layoutParams = surfaceView.getLayoutParams();
if (ratio_width > ratio_height){
layoutParams.width = (int) (surfaceView_Height * aspectratio);
layoutParams.height = surfaceView_Height;
}else{
layoutParams.width = surfaceView_Width;
layoutParams.height = (int) (surfaceView_Width / aspectratio);
}
surfaceView.setLayoutParams(layoutParams);
}
call above function before calling
mediaPlayer.start();
I met the same problem,after i look into VideoView source code in API 23,i found the good method,here is my solution,we can create a custom SurfaceView and override onMeasure(),then here you go,use VideoSurfaceView to play the video.
public class VideoSurfaceView extends SurfaceView implements MediaPlayer.OnVideoSizeChangedListener {
private int mVideoWidth;
private int mVideoHeight;
public VideoSurfaceView(Context context) {
super(context);
}
public VideoSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public VideoSurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
/**
* Set video size.
*
* #see MediaPlayer#getVideoWidth()
* #see MediaPlayer#getVideoHeight()
*/
public void setVideoSize(int videoWidth, int videoHeight) {
mVideoWidth = videoWidth;
mVideoHeight = videoHeight;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//Log.i("####", "onMeasure(" + MeasureSpec.toString(widthMeasureSpec) + ", "
// + MeasureSpec.toString(heightMeasureSpec) + ")");
int width = getDefaultSize(mVideoWidth, widthMeasureSpec);
int height = getDefaultSize(mVideoHeight, heightMeasureSpec);
if (mVideoWidth > 0 && mVideoHeight > 0) {
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthSpecMode == MeasureSpec.EXACTLY && heightSpecMode == MeasureSpec.EXACTLY) {
// the size is fixed
width = widthSpecSize;
height = heightSpecSize;
// for compatibility, we adjust size based on aspect ratio
if (mVideoWidth * height < width * mVideoHeight) {
//Log.i("###", "image too wide, correcting");
width = height * mVideoWidth / mVideoHeight;
} else if (mVideoWidth * height > width * mVideoHeight) {
//Log.i("###", "image too tall, correcting");
height = width * mVideoHeight / mVideoWidth;
}
} else if (widthSpecMode == MeasureSpec.EXACTLY) {
// only the width is fixed, adjust the height to match aspect ratio if possible
width = widthSpecSize;
height = width * mVideoHeight / mVideoWidth;
if (heightSpecMode == MeasureSpec.AT_MOST && height > heightSpecSize) {
// couldn't match aspect ratio within the constraints
height = heightSpecSize;
}
} else if (heightSpecMode == MeasureSpec.EXACTLY) {
// only the height is fixed, adjust the width to match aspect ratio if possible
height = heightSpecSize;
width = height * mVideoWidth / mVideoHeight;
if (widthSpecMode == MeasureSpec.AT_MOST && width > widthSpecSize) {
// couldn't match aspect ratio within the constraints
width = widthSpecSize;
}
} else {
// neither the width nor the height are fixed, try to use actual video size
width = mVideoWidth;
height = mVideoHeight;
if (heightSpecMode == MeasureSpec.AT_MOST && height > heightSpecSize) {
// too tall, decrease both width and height
height = heightSpecSize;
width = height * mVideoWidth / mVideoHeight;
}
if (widthSpecMode == MeasureSpec.AT_MOST && width > widthSpecSize) {
// too wide, decrease both width and height
width = widthSpecSize;
height = width * mVideoHeight / mVideoWidth;
}
}
} else {
// no size yet, just adopt the given spec sizes
}
setMeasuredDimension(width, height);
}
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
mVideoWidth = mp.getVideoWidth();
mVideoHeight = mp.getVideoHeight();
if (mVideoWidth != 0 && mVideoHeight != 0) {
getHolder().setFixedSize(mVideoWidth, mVideoHeight);
requestLayout();
}
}
}

MediaPlayer playing sound but not video

I'm trying to play a video from Android using a SurfaceView.
I can load the video, the sound is played correctly but I can't see the video.
Here is my activity :
public class VideoTest extends Activity implements OnBufferingUpdateListener, OnCompletionListener, OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback, OnErrorListener {
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;
public static final String MEDIA = "media";
private static final int LOCAL_AUDIO = 1;
public static final int STREAM_AUDIO = 2;
private static final int RESOURCES_AUDIO = 3;
private static final int LOCAL_VIDEO = 4;
public static final int STREAM_VIDEO = 5;
private boolean mIsVideoSizeKnown = false;
private boolean mIsVideoReadyToBePlayed = false;
private RelativeLayout layout;
/**
*
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mPreview = new SurfaceView(this);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
extras = getIntent().getExtras();
mPreview.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
layout = new RelativeLayout(this);
layout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
layout.addView(mPreview, 0);
setContentView(layout);
}
private void playVideo(Integer Media) {
doCleanUp();
try {
mMediaPlayer = MediaPlayer.create(this, R.raw.video);
mMediaPlayer.setDisplay(holder);
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setOnErrorListener(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 + " pos : " + mMediaPlayer.getCurrentPosition() + " / " + mMediaPlayer.getDuration());
if (mMediaPlayer.isPlaying()) {
Log.d(TAG, "Playing");
} else {
mMediaPlayer.start();
}
}
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. Width : " + j + ", height : " + k);
holder = surfaceholder;
mMediaPlayer.setDisplay(holder);
mIsVideoSizeKnown = true;
mVideoWidth = j;
mVideoHeight = k;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void surfaceDestroyed(SurfaceHolder surfaceholder) {
Log.d(TAG, "surfaceDestroyed called");
}
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated called");
playVideo(extras.getInt(MEDIA));
}
#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 " + mVideoWidth + "x" + mVideoHeight);
int width = mPreview.getWidth();
int height = mPreview.getHeight();
float boxWidth = width;
float boxHeight = height;
float videoWidth = mMediaPlayer.getVideoWidth();
float videoHeight = mMediaPlayer.getVideoHeight();
Log.i(TAG, String.format("startVideoPlayback # video %dx%d - box %dx%d", (int) videoWidth, (int) videoHeight, width, height));
float wr = boxWidth / videoWidth;
float hr = boxHeight / videoHeight;
float ar = videoWidth / videoHeight;
if (wr > hr) {
width = (int) (boxHeight * ar);
} else {
height = (int) (boxWidth / ar);
}
Log.i(TAG, String.format("Scaled to %dx%d", width, height));
holder.setFixedSize(width, height);
mMediaPlayer.start();
}
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
Log.e(TAG, "ERROR called : " + arg1 + ", " + arg2);
return false;
}
}
The onVideoSizeChanged function is never called but the onPrepared and surfaceChanged are called.
Thus the startVideoPlayback function is called, but the video width and height are 0.
My video is playing, as I can hear the sound, but nothing is displayed on the screen.
I also tried to give raw width and height to the setFixedSize function of the SurfaceHolder object but I still don't have anything displayed.
Can you help me?
I'm using Android 8
EDIT
Here is the log I have when I'm playing a video from the resources :
WARN info/warning (1, 35)
WARN info/warning (1, 44)
DEBUG Duration : 101248
DEBUG surfaceChanged called. Width : 480, height : 270
INFO Info (1,35)
INFO Info (1,44)
DEBUG onPrepared called
VERBOSE startVideoPlayback 480x270
INFO startVideoPlayback # video 0x0 - box 480x270
INFO Scaled to 480x0
DEBUG surfaceDestroyed called
EDIT 2
I tried with another video and it's working.
Here are the specifications of the "not working" video :
Container : MP4 - QuickTime
Rate : 2 340 Kbps
Format : H.264/MPEG-4-AVC
Size : 1280*640
Aspect pixel : undefined
Image proportion : 2.000
Encoding profile : Baseline#L3.1
Here are the specifications for the working video :
Container : MP4 - QuickTime
Rate : 537 Kbps
Format : H.264/MPEG-4-AVC
Size : 640*360
Aspect pixel : undefined
Image proportion : 16:9
Encoding profile : Baseline#L3.0
Do you know what's wrong with the first video ?
Some things to try:
1) Should you be calling mMediaPlayer.prepareAsync() in your playVideo method?
2) Try removing your if statement in onPrepared
3) I would call holder.setSizeFromLayout(); and then mMediaPlayer.start() from your onPrepared callback (rather than onBufferingUpdate).

android mediaplayer over 3g connection not work but work on wifi

I am working on a project that uses videoView to display a .mp4 video from url. My code works in the emulator fine but on the physical device (Samsung siii) it only works over WiFi and not work over 3G.
youtube video works fine over 3g and and i test same video with other player vplayer and itz wrok fine..
this is my code
package com.video;
public class StreamingVideoPlayer extends Activity implements
OnCompletionListener, OnErrorListener, OnInfoListener,
OnBufferingUpdateListener, OnPreparedListener, OnSeekCompleteListener,
OnVideoSizeChangedListener, SurfaceHolder.Callback,
MediaController.MediaPlayerControl {
MediaController controller;
Display currentDisplay;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
MediaPlayer mediaPlayer;
View mainView;
TextView statusView;
int videoWidth = 0;
int videoHeight = 0;
boolean readyToPlay = false;
public final static String LOGTAG = "STREAMING_VIDEO_PLAYER";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mainView = this.findViewById(R.id.MainView);
statusView = (TextView) this.findViewById(R.id.StatusTextView);
surfaceView = (SurfaceView) this.findViewById(R.id.SurfaceView);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mediaPlayer = new MediaPlayer();
statusView.setText("MediaPlayer Created");
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnInfoListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnVideoSizeChangedListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
//String filePath = "http://sffsapps.s3.amazonaws.com/02-benefits-100dc.mp4";
// String filePath="http://100dcapps.s3.amazonaws.com/droidtest/index.droid.mp4";
String filePath="https://100dcapps.s3.amazonaws.com/droidtest/index.mp4";
try {
mediaPlayer.setDataSource(filePath);
} catch (IllegalArgumentException e) {
Log.v(LOGTAG, e.getMessage());
finish();
} catch (IllegalStateException e) {
Log.v(LOGTAG, e.getMessage());
finish();
} catch (IOException e) {
Log.v(LOGTAG, e.getMessage());
finish();
}
statusView.setText("MediaPlayer DataSource Set");
currentDisplay = getWindowManager().getDefaultDisplay();
controller = new MediaController(this);
}
public void surfaceCreated(SurfaceHolder holder) {
Log.v(LOGTAG, "surfaceCreated Called");
mediaPlayer.setDisplay(holder);
statusView.setText("MediaPlayer Display Surface Set");
try {
mediaPlayer.prepareAsync();
} catch (IllegalStateException e) {
Log.v(LOGTAG, "IllegalStateException " + e.getMessage());
finish();
}
statusView.setText("MediaPlayer Preparing");
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Log.v(LOGTAG, "surfaceChanged Called");
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.v(LOGTAG, "surfaceDestroyed Called");
}
public void onCompletion(MediaPlayer mp) {
Log.v(LOGTAG, "onCompletion Called");
statusView.setText("MediaPlayer Playback Completed");
}
public boolean onError(MediaPlayer mp, int whatError, int extra) {
Log.v(LOGTAG, "onError Called");
statusView.setText("MediaPlayer Error");
if (whatError == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
Log.v(LOGTAG, "Media Error, Server Died " + extra);
} else if (whatError == MediaPlayer.MEDIA_ERROR_UNKNOWN) {
Log.v(LOGTAG, "Media Error, Error Unknown " + extra);
}
return false;
}
public boolean onInfo(MediaPlayer mp, int whatInfo, int extra) {
statusView.setText("MediaPlayer onInfo Called");
if (whatInfo == MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING) {
Log.v(LOGTAG, "Media Info, Media Info Bad Interleaving " + extra);
} else if (whatInfo == MediaPlayer.MEDIA_INFO_NOT_SEEKABLE) {
Log.v(LOGTAG, "Media Info, Media Info Not Seekable " + extra);
} else if (whatInfo == MediaPlayer.MEDIA_INFO_UNKNOWN) {
Log.v(LOGTAG, "Media Info, Media Info Unknown " + extra);
} else if (whatInfo == MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING) {
Log.v(LOGTAG, "MediaInfo, Media Info Video Track Lagging " + extra);
} /*
* Android version 2.0 or higher else if (whatInfo ==
* MediaPlayer.MEDIA_INFO_METADATA_UPDATE) { Log.v(LOGTAG,
* "MediaInfo, Media Info Metadata Update " + extra); }
*/
return false;
}
public void onPrepared(MediaPlayer mp) {
Log.v(LOGTAG, "onPrepared Called");
statusView.setText("MediaPlayer Prepared");
videoWidth = mp.getVideoWidth();
videoHeight = mp.getVideoHeight();
Log.v(LOGTAG, "Width: " + videoWidth);
Log.v(LOGTAG, "Height: " + videoHeight);
if (videoWidth > currentDisplay.getWidth()
|| videoHeight > currentDisplay.getHeight()) {
float heightRatio = (float) videoHeight
/ (float) currentDisplay.getHeight();
float widthRatio = (float) videoWidth
/ (float) currentDisplay.getWidth();
if (heightRatio > 1 || widthRatio > 1) {
if (heightRatio > widthRatio) {
videoHeight = (int) Math.ceil((float) videoHeight
/ (float) heightRatio);
videoWidth = (int) Math.ceil((float) videoWidth
/ (float) heightRatio);
} else {
videoHeight = (int) Math.ceil((float) videoHeight
/ (float) widthRatio);
videoWidth = (int) Math.ceil((float) videoWidth
/ (float) widthRatio);
}
}
}
surfaceView.setLayoutParams(new LinearLayout.LayoutParams(videoWidth,
videoHeight));
controller.setMediaPlayer(this);
controller.setAnchorView(this.findViewById(R.id.MainView));
controller.setEnabled(true);
controller.show();
mp.start();
statusView.setText("MediaPlayer Started");
}
public void onSeekComplete(MediaPlayer mp) {
Log.v(LOGTAG, "onSeekComplete Called");
}
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
Log.v(LOGTAG, "onVideoSizeChanged Called");
videoWidth = mp.getVideoWidth();
videoHeight = mp.getVideoHeight();
Log.v(LOGTAG, "Width: " + videoWidth);
Log.v(LOGTAG, "Height: " + videoHeight);
if (videoWidth > currentDisplay.getWidth()
|| videoHeight > currentDisplay.getHeight()) {
float heightRatio = (float) videoHeight
/ (float) currentDisplay.getHeight();
float widthRatio = (float) videoWidth
/ (float) currentDisplay.getWidth();
if (heightRatio > 1 || widthRatio > 1) {
if (heightRatio > widthRatio) {
videoHeight = (int) Math.ceil((float) videoHeight
/ (float) heightRatio);
videoWidth = (int) Math.ceil((float) videoWidth
/ (float) heightRatio);
} else {
videoHeight = (int) Math.ceil((float) videoHeight
/ (float) widthRatio);
videoWidth = (int) Math.ceil((float) videoWidth
/ (float) widthRatio);
}
}
}
surfaceView.setLayoutParams(new LinearLayout.LayoutParams(videoWidth,
videoHeight));
}
public void onBufferingUpdate(MediaPlayer mp, int bufferedPercent) {
statusView.setText("MediaPlayer Buffering: " + bufferedPercent + "%");
Log.v(LOGTAG, "MediaPlayer Buffering: " + bufferedPercent + "%");
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
public int getBufferPercentage() {
return 0;
}
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
public void pause() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
}
public void seekTo(int pos) {
mediaPlayer.seekTo(pos);
}
public void start() {
mediaPlayer.start();
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
/*if (controller.isShowing()) {
controller.hide();
} else {*/
controller.show();
//}
return false;
}
}

SurfaceView height + width gets ignored

The following script works flawless, but the size of my videoplayer will get f'd after changing my surfaceview from portrait to landscape. Tried several options like setFixedSize(), setSizeFromLayout() and removing everything which involves my width + height from my surfaceview. Does anyone knows whats wrong with the code below?
Or did someone have the same problem in the past?
package com.list;
import io.vov.vitamio.MediaPlayer;
import io.vov.vitamio.MediaPlayer.OnBufferingUpdateListener;
import io.vov.vitamio.MediaPlayer.OnCompletionListener;
import io.vov.vitamio.MediaPlayer.OnPreparedListener;
import io.vov.vitamio.MediaPlayer.OnVideoSizeChangedListener;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class mediaPlayer 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 boolean mIsVideoSizeKnown = false;
private boolean mIsVideoReadyToBePlayed = false;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.mediaplayer);
mPreview = (SurfaceView) findViewById(R.id.surface);
holder = mPreview.getHolder();
holder.addCallback(this);
}
private void playVideo() {
doCleanUp();
try {
mMediaPlayer = new MediaPlayer(this);
Intent myIntent = this.getIntent();
String url = myIntent.getStringExtra("url");
mMediaPlayer.setDataSource(url);
mMediaPlayer.setDisplay(holder);
mMediaPlayer.prepareAsync();
mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
} 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");
mMediaPlayer.release();
}
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;
}
Log.v("afmeting", "->" +width+"px bij "+height+"px");
mIsVideoSizeKnown = true;
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" + i + " " + j + " " + k);
}
public void surfaceDestroyed(SurfaceHolder surfaceholder) {
Log.d(TAG, "surfaceDestroyed called");
}
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated called");
playVideo();
}
#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.setSizeFromLayout();
mMediaPlayer.start();
}
}
Same problem here:
I believe the problem is the Vitamio library as I have experienced a similar problem when dealing with the Vitamio SDK. Resizing didn't work for me, when using a SurfaceView and invoking setLayoutParams(ViewGroup.LayoutParams params). The below code works fine using the standard Android media-framework, but importing the vitamio packages breaks it.
RelativeLayout.LayoutParams video_VIEWLAYOUT = (RelativeLayout.LayoutParams) videoView.getLayoutParams();
video_VIEWLAYOUT.width = screenWidth;
video_VIEWLAYOUT.height = (int) (((float)videoHeight / (float)videoWidth) *(float)screenWidth);
videoView.setLayoutParams(video_VIEWLAYOUT);
My recommendation would be to try using the io.vov.vitamio.widget.VideoView instead of a android.view.SurfaceView.
use this method and call it inside onConfigurationChanged method :
private void setVideoSize() {
// // Get the dimensions of the video
// mVideoView is your video view object.
int videoWidth = mVideoView.getVideoWidth();
int videoHeight = mVideoView.getVideoHeight();
float videoProportion = (float) videoWidth / (float) videoHeight;
// Get the width of the screen
int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
int screenHeight = getWindowManager().getDefaultDisplay().getHeight();
float screenProportion = (float) screenWidth / (float) screenHeight;
// Get the SurfaceView layout parameters
android.view.ViewGroup.LayoutParams lp = mVideoView.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
mVideoView.setLayoutParams(lp);
}
Now on change of orientation your videoview will be resized.

Categories

Resources