在Android中,使用exoplayer,如何用与设备长宽比不同的视频填充surfaceview?

In Android, using exoplayer, how to fill surfaceview with a video that does not have the same aspect ratio with the device?

我有一个 activity 使用 ExoPlayer 播放视频。当我全屏时,除非设备的纵横比等于视频的纵横比,否则我会在视频的顶部和底部出现小黑条。

布局是这样的:

<com.google.android.exoplayer.AspectRatioFrameLayout
    android:id="@+id/video_frame"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentBottom="true">

    <SurfaceView android:id="@+id/surface_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="fill_vertical"/>

    <View android:id="@+id/shutter"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/black"/>

</com.google.android.exoplayer.AspectRatioFrameLayout>

我希望

aspectRatioFrameLayout.setAspectRatio(mVideo.getAspectRatio());

会解决问题,但我没有成功。 有没有办法让视频充满屏幕,即使部分视频从屏幕上被截掉?

您可以删除 com.google.android.exoplayer.AspectRatioFrameLayout

接下来,在 match_parent 上放置一个简单的 FrameLayout 宽度和高度。

请注意,SurfaceView 应保持宽度和高度 = match_parent

说明:AspectRatioFrameLayout是根据真实的视频比例(根据宽高和pixelRatio计算)设置正确的视图高度。如果您不想这样做,Exoplayer 仍然可以像以前一样在 SurfaceView 上显示视图。如果 SurfaceView 不是 @Override,则不会有宽高比。

有一种最快的方法可以让视频充满屏幕。 转到 SimpleExoPlayerView.java class,将 resizeModeAspectRatioFrameLayout.RESIZE_MODE_FIT 更改为 AspectRatioFrameLayout.RESIZE_MODE_FILLRESIZE_MODE_FILL 将忽略指定的纵横比。 如果您在项目中使用 ExoPlayer 作为模块,请使用这种方式。

已更新 如果你使用 ExoPlayer 作为库,他们有一个方法 setResizeMode()。 您刚刚在视图中设置为 AspectRatioFrameLayout.RESIZE_MODE_FILLsimpleExoPlayerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FILL) 就这些!

这也可以在 XML 中完成,如果您使用 SimpleExoPlayerView

只需添加 app:resize_mode="zoom" 即可保持视频的宽高比,如果您不关心宽高比,则添加 app:resize_mode="fill"

<com.google.android.exoplayer2.ui.SimpleExoPlayerView
            android:id="@+id/video"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:resize_mode="zoom" />

只需在 xml 中使用下面这行。它将完美运行。

app:resize_mode="fill"