检测视频是否以纵向/横向拍摄

时间:2017-07-25 05:43:54

标签: android android-layout android-orientation

我想确认我正在做的事情确实是正确的方式,因为有些元素表现出意外。

首先,我有一个横向和纵向布局,据我所知,这样做会自动检测手机是否处于纵向/横向模式:

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

然后,当用户从图库中选择视频时,我会检查视频是采用横向还是纵向拍摄(在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:

我注意到这只会在第一次启动活动时发生,如果我按下后退按钮并再次选择相同的视频,布局就像我想要的那样。

编辑2:

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

1 个答案:

答案 0 :(得分:1)

这就是我最后要做的。

我不是使用MediaMetadataRetriever来获取宽度和高度,而是先从视频文件中检索Bitmap,然后根据Bitmap的宽度和高度来设置方向,如下所示:

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");

    }
}