How To Determine Video Width And Height On Android
I have a video file and I want to get width and height of video. I don't want to play it, just to get size. I've tried to use MediaPlayer: MediaPlayer mp = new MediaPlayer(); mp.se
Solution 1:
This works in API level 10 and up:
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource("/path/to/video.mp4");
int width = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
int height = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
retriever.release();
Solution 2:
In some cases, we are unable to read the metadata. To ensure that we get the width and height, it is best to create a Bitmap
using MediaMetadataRetriever
, then get the width and height from the created Bitmap
, as shown below:
publicintgetVideoWidthOrHeight(File file, String widthOrHeight) {
MediaMetadataRetrieverretriever=null;
Bitmapbmp=null;
FileInputStreaminputStream=null;
intmWidthHeight=0;
try {
retriever = newMediaMetadataRetriever();
inputStream = newFileInputStream(file.getAbsolutePath());
retriever.setDataSource(inputStream.getFD());
bmp = retriever.getFrameAtTime();
if (widthOrHeight.equals("width")){
mWidthHeight = bmp.getWidth();
}else {
mWidthHeight = bmp.getHeight();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
} finally{
if (retriever != null){
retriever.release()
}if (inputStream != null){
inputStream.close()
}
}
return mWidthHeight;
}
You can call the above method like this:
// Get the video widthint mVideoWidth = getVideoWidthOrHeight(someFile, "width");
// Get the video heightint mVideoHeight = getVideoWidthOrHeight(someFile, "height");
Solution 3:
This worked for me
videoView.setOnPreparedListener(newMediaPlayer.OnPreparedListener() {
@OverridepublicvoidonPrepared(final MediaPlayer mp) {
intwidth= mp.getVideoWidth();
intheight= mp.getVideoHeight();
}
});
Solution 4:
API level 7 solution:
// get video dimensionsMediaPlayermp=newMediaPlayer();
try {
mp.setDataSource(filename);
mp.prepare();
mp.setOnVideoSizeChangedListener(newOnVideoSizeChangedListener() {
@OverridepublicvoidonVideoSizeChanged(MediaPlayer mp, int width, int height) {
intorient= -1;
if(width < height)
orient = 1;
elseorient=0;
}
});
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Solution 5:
This set of utilities to work with the Size abstraction in Android.
It contains an class SizeFromVideoFile.java You can use it like this:
ISizesize=newSizeFromVideoFile(videoFilePath);
size.width();
size.hight();
Post a Comment for "How To Determine Video Width And Height On Android"