Android Videoview Issue - android

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.

Related

How resize TextureView to fullscreen when rotation 90?

I using a TextureView to play video:
I have to use rotation=90 to display video correct orientation when record video
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#777777" >
<TextureView
android:id="#+id/textureView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:rotation="90"
android:layout_alignParentTop="true" />
i try set setTransform of TextureView to resize video to fullsreen, but it not working:
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
Surface surface = new Surface(surfaceTexture);
try {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(FILE_NAME);
mMediaPlayer.setSurface(surface);
mMediaPlayer.setLooping(false);
mMediaPlayer.prepareAsync();
updateTextureViewScaling(width,height);
// Play video when the media source is ready for playback.
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
} catch (IllegalArgumentException e) {
Log.d(TAG, e.getMessage());
} catch (SecurityException e) {
Log.d(TAG, e.getMessage());
} catch (IllegalStateException e) {
Log.d(TAG, e.getMessage());
} catch (IOException e) {
Log.d(TAG, e.getMessage());
}
}
private void updateTextureViewScaling(int viewWidth, int viewHeight) {
float scaleX = 1.0f;
float scaleY = 1.0f;
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int VIDEO_HEIGHT = displayMetrics.heightPixels;
int VIDEO_WIDTH = displayMetrics.widthPixels;
if (VIDEO_WIDTH > viewWidth && VIDEO_WIDTH > viewHeight) {
scaleX = (float) VIDEO_WIDTH / viewWidth;
scaleY = (float) VIDEO_HEIGHT / viewHeight;
} else if (VIDEO_WIDTH < viewWidth && VIDEO_HEIGHT < viewHeight) {
scaleY = (float) viewWidth / VIDEO_WIDTH;
scaleX = (float) viewHeight / VIDEO_HEIGHT;
} else if (viewWidth > VIDEO_WIDTH) {
scaleY = ((float) viewWidth / VIDEO_WIDTH) / ((float) viewHeight / VIDEO_HEIGHT);
} else if (viewHeight > VIDEO_HEIGHT) {
scaleX = ((float) viewHeight / VIDEO_WIDTH) / ((float) viewWidth / VIDEO_WIDTH);
}
// Calculate pivot points, in our case crop from center
int pivotPointX = viewWidth / 2;
int pivotPointY = viewHeight / 2;
Matrix matrix = new Matrix();
matrix.setScale(scaleX, scaleY, pivotPointX, pivotPointY);
textureView.setTransform(matrix);
}
Target result:
Image 1: not set android:rotation="90"
Image 2: set android:rotation="90"
How can set width and height of video to fullscreen:
i had log:
Width and Height in onSurfaceTextureAvailable = size of Screen.
My problem had fixed by:
put TextureView in a FrameLayout
and update function updateTextureViewScaling
private void updateTextureViewScaling(int viewWidth, int viewHeight) {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) textureView.getLayoutParams();
params.width = viewHeight;
params.height =viewWidth;
params.gravity= Gravity.CENTER;
textureView.setLayoutParams(params);
}
Overide this method in Activity:
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
textview.setRotation(90);
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
textview.setRotation(0);
}
}
in Android Manifest file mention this under activity
android:configChanges="orientation|screenSize".

Issue when playing video in local and url path

I play the video in VideoView
When I play from SD Card, it shows correct width and height in full screen. When I try to play from server, video Width is smaller and the video is re-sized.
How can I play the video in original size and full screen?
Take a look at the documentation and implement the onPrepared method like the following code:
//prepare the video
public void onPrepared(MediaPlayer mp) {
progressBarWait.setVisibility(View.GONE);
//First get the size of the video
int videoWidth = player.getVideoWidth();
int videoHeight = player.getVideoHeight();
float videoProportion = (float) videoWidth / (float) videoHeight;
//get the size of the screen
int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
int screenHeight = getWindowManager().getDefaultDisplay().getHeight();
float screenProportion = (float) screenWidth / (float) screenHeight;
//Adjust
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;
}
surfaceViewFrame.setLayoutParams(lp);
if (!player.isPlaying()) {
player.start();
}
surfaceViewFrame.setClickable(true);
}

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

How to Record Streaming Video?

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.

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