根据视频宽度和高度旋转屏幕

Rotate screen depending on video width and height

我目前正在通过执行以下操作检测所选视频的宽度和高度:

MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
    mediaMetadataRetriever.setDataSource(this, mVideoUri);
    String height = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
    String width = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);

清单中的activity:

<activity android:name=".TrimVideoActivity"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar.FullScreen"
        />

如果我敬酒宽度和高度它总是 returns w : 1920 h : 1080 无论视频的尺寸是多少。我认为它返回的是设备的宽度和高度。

我是否遗漏或做错了什么?


编辑

按照@VladMatvienko 建议的link,我能够获得视频文件的正确宽度和高度,这就是我实现它的方式:

MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    Bitmap bmp = null;
    retriever.setDataSource(this, mVideoUri);
    bmp = retriever.getFrameAtTime();

    String videoWidth = String.valueOf(bmp.getWidth());
    String videoHeight = String.valueOf(bmp.getHeight());

现在我想根据结果旋转屏幕 (width/height),我尝试了以下操作:

int w = Integer.parseInt(videoWidth);
    int h = Integer.parseInt(videoHeight);


    if (w > h) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);


    } if(w < h) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    }

但是,当宽度小于高度时,屏幕总是旋转为横向,而不是设置为纵向?

我决定添加一个答案来解释我是如何解决这个问题的。

我最初方法的问题:

MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(this, mVideoUri);
String height = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
String width = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);

问题是视频可能没有我正在寻找的元数据,这将导致 nullpointerexception

为了避免这个问题,我可以从视频中获取一帧(作为位图)并通过执行以下操作从该位图中获取宽度和高度:

MediaMetadataRetriever retriever = new MediaMetadataRetriever();
Bitmap bmp;
retriever.setDataSource(this, mVideoUri);
bmp = retriever.getFrameAtTime();

但是,这会带来另一个问题,您可能没有。在我的例子中,我想从 first/nearest 帧开始,因为如果在捕获视频期间屏幕旋转,那么帧的 width/height 将会改变,所以我只添加了 1至 getFrameAtTime(1).


现在我可以根据视频文件的宽度和高度旋转屏幕:

try {
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    Bitmap bmp;
    retriever.setDataSource(this, mVideoUri);
    bmp = retriever.getFrameAtTime(1);

    int videoWidth = bmp.getWidth();
    int videoHeight = bmp.getHeight();

    if (videoWidth > videoHeight) {
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }
    if (videoWidth < videoHeight) {
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

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

当然会在 onCreate.

中调用上面的内容

希望这对那里的人有所帮助。