检测视频是否以人像/风景拍摄

Cla*_*ssA 5 android android-layout android-orientation

我想确认一下,我所做的确实是正确的方法,因为某些元素的行为异常。

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

- layout
   - activity_video_player.xml
 - layout-land
   - activity_video_player.xml
Run Code Online (Sandbox Code Playgroud)

然后,当用户从图库中选择一个视频时,我通过执行以下操作(在中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);
}
Run Code Online (Sandbox Code Playgroud)

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

所以我的应用程序流程是:

MainActivity --> SelectvidButton --> Gallery Intent --> VideoPlayActivity
Run Code Online (Sandbox Code Playgroud)

我的问题

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


编辑1:

我注意到,只有在首次启动活动时才会发生这种情况,如果我按“后退”按钮并再次选择相同的视频,则布局完全像我想要的那样。


编辑2:

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

Cla*_*ssA 7

这是我最终做的。

我没有使用MediaMetadataRetriever获取宽度和高度,而是首先Bitmap从视频文件中检索 a ,然后根据 的宽度和高度设置方向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");

    }
}
Run Code Online (Sandbox Code Playgroud)