检测视频是否拍摄于 portrait/landscape

Detecting if video was taken in portrait/landscape

我想确认我所做的确实是正确的方法,因为某些元素的行为出乎意料。

首先,我有横向和纵向布局,据我了解,这样做会自动检测 phone 是否处于 portrait/landscape 模式:

- layout
   - activity_video_player.xml
 - layout-land
   - activity_video_player.xml

然后当用户 select 从图库中观看视频时,我检查视频是横向还是纵向,方法是这样做(在 OnCreate 内):

int w;
int h;

MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(this, videoURI);
String height = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
String width = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
w = Integer.parseInt(width);
h = Integer.parseInt(height);

if (w > h) {  
    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

我已经对此进行了测试并且工作正常,但我注意到我的一些 xml 元素(播放按钮)放置不正确。

所以我的应用流程是:

MainActivity --> SelectvidButton --> Gallery Intent --> VideoPlayActivity

我的问题

这是正确的做法吗?如果是,是否有任何原因导致某些 xml 元素放置不正确?


编辑 1:

我注意到只有在第一次启动 activity 时才会发生这种情况,如果我按下后退按钮并再次 select 同一视频,布局完全符合我的要求成为。


编辑 2:

我还注意到,只有前一个 activity (MainActivity) 与 selected 视频的方向相同时才会发生这种情况。

这是我最后做的。

我没有使用MediaMetadataRetriever获取宽度和高度,而是先从视频文件中检索一个Bitmap,然后根据[=12=的宽度和高度设置方向],如下图:

private void rotateScreen() {
    try {
        //Create a new instance of MediaMetadataRetriever
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        //Declare the Bitmap
        Bitmap bmp;
        //Set the video Uri as data source for MediaMetadataRetriever
        retriever.setDataSource(this, mVideoUri);
        //Get one "frame"/bitmap - * NOTE - no time was set, so the first available frame will be used
        bmp = retriever.getFrameAtTime();

        //Get the bitmap width and height
        videoWidth = bmp.getWidth();
        videoHeight = bmp.getHeight();

        //If the width is bigger then the height then it means that the video was taken in landscape mode and we should set the orientation to landscape
        if (videoWidth > videoHeight) {
            //Set orientation to landscape
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        //If the width is smaller then the height then it means that the video was taken in portrait mode and we should set the orientation to portrait
        if (videoWidth < videoHeight) {
            //Set orientation to portrait
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

    } catch (RuntimeException ex) {
        //error occurred
        Log.e("MediaMetadataRetriever", "- Failed to rotate the video");

    }
}