我有一个视频文件,我从以下代码获得分辨率(3840x2160)和旋转(0):
MediaMetadataRetriever retr = new MediaMetadataRetriever();
retr.setDataSource(mVideoFile);
String height = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
String width = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
String rotation = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
但是actullay,视频旋转角度(度数)不正确,应该为90,2160x3840分辨率,因此我的视频始终无法在我的Android应用程序中正确显示。
有趣的是,某些第三方视频播放器(例如VLC)可以检测到该视频文件的实际旋转,并且显示也可以,它们是如何做到的?
最佳答案
为时已晚,但可能会帮助将来的访客。
下一行将返回视频的旋转。四个可能的值将是0,90,180,270。
rotation = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION));
如果旋转角度为90或270,则宽度和高度将被转置。
Android MediaMetadataRetriever wrong video height and width
如果旋转角度为90或270,请滑动宽度和高度。
if(rotation == 90 || rotation == 270)
{
int swipe = width;
width = height;
height = swipe;
}
以下是完整的代码。我将结果与MXPlayer的结果相同。
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.";
}
}
以下是用于设置屏幕方向的代码。
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();
}
在Build.VERSION_CODES.JELLY_BEAN_MR1以下版本上运行的设备怎么办?
答:我不知道。但是以上代码将在大多数设备上运行。
以下是最佳答案:https://stackoverflow.com/a/56337044/8199772