It's too late but probably it will help future visitors.
Following line will return rotation of video. Four possible value will be 0,90,180,270.
rotation = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION));
If the rotation is 90 or 270 the width and height will be transposed.
Android MediaMetadataRetriever wrong video height and width
So swipe the width and height, if rotation is 90 or 270.
if(rotation == 90 || rotation == 270)
{
int swipe = width;
width = height;
height = swipe;
}
Following is the complete code. I compare the result with MXPlayer result is same.
public static String getVideoResolution(File file)
{
try
{
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(file.getPath());
int width = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
int height = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
int rotation = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
rotation = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION));
}
retriever.release();
if(rotation != 0)
{
if(rotation == 90 || rotation == 270)
{
int swipe = width;
width = height;
height = swipe;
}
}
return width + " x " + height;
}
catch (Exception e)
{
e.printStackTrace();
return "Information not found.";
}
}
Following is the code for setting screen orientation.
int width;
int height;
int rotation = 0;
try {
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(filePath);
width = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
height = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
rotation = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION));
}
retriever.release();
if(rotation != 0)
{
if(rotation == 90 || rotation == 270)
{
int swipe = width;
width = height;
height = swipe;
}
}
this.setRequestedOrientation(width < height ? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT : ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
catch (Exception e){
e.printStackTrace();
}
What about devices that run on Version below Build.VERSION_CODES.JELLY_BEAN_MR1?
Ans: I didn't know. But above code will work on most of devices.
Following is the best answer: https://stackoverflow.com/a/56337044/8199772