ExoPlayer的PlayerView如何使用TextureView代替SurfaceView?

How to use TextureView instead of SurfaceView with PlayerView of ExoPlayer?

我知道可以在 ExoPlayer 中使用 TextureView。但是我找不到任何关于如何以正确方式实现此功能的示例。你能帮我解决这个问题吗?

来自 the documentation:

If you require fine-grained control over the player controls and the Surface onto which video is rendered, you can set the player’s target SurfaceView, TextureView, SurfaceHolder or Surface directly using SimpleExoPlayer’s setVideoSurfaceView, setVideoTextureView, setVideoSurfaceHolder and setVideoSurface methods respectively.

所以这里的相关部分是 setVideoTextureView()。类似于:

SimpleExoPlayer player = ExoPlayerFactory.newSimpleInstance(context, trackSelector);
TexturView textureView = findViewById(texture_view);
player.setVideoTextureView(textureView);

您还可以通过 TextureViewsetSurfaceTextureViewListener()SurfaceTexture 创建 Surface。参见 TextureView's documentation and 。然后你可以在播放器上调用 setSurface(...)

但是既然 SimpleExoPlayerTextureView setter(我们在旧的 ExoPlayer 中并不总是有这个),你真的不需要再这样做了。另外作为另一个参考,这里是the issue on ExoPlayer关于支持这个。

作为旁注,您可以看到 SurfaceViewTextureView here 之间的差异。一般建议使用 SurfaceView,但也有细微差别。

[编辑]

如果您想即时执行此操作,您可以像我上面写的那样实例化 SimpleExoPlayer(而不是 SimpleExoPlayerView),然后在您的 PlayerView(您可以在 XML 中定义或动态定义)。

如果您不需要即时设置 surface/texture 视图,那么您可以通过 [=36= 在布局 XML 中的 PlayerView 上设置它].

PlayerView 有一个 xml 属性 surface_type,让您选择是要使用 SurfaceView 还是 TextureView

(注意:SimpleExoPlayerView 在最近的版本中已重命名为 PlayerView,因为它仅依赖于 Player 界面,不再依赖于 SimpelExoPlayerView。)

您可以选择texture_view、surface_view(默认)或none。有关详细信息,请参阅 the main section of the JavaDoc of PlayerView

<com.google.android.exoplayer2.ui.PlayerView android:id="@+id/player_view"
     app:surface_type="texture_view"
     android:layout_width="match_parent"
     android:layout_height="match_parent"/>

注意,TextureView只能用于硬件加速window。在软件中渲染时,TextureView 不会绘制任何内容。所以在设置表面类型后

<com.google.android.exoplayer2.ui.PlayerView android:id="@+id/player_view"
 app:surface_type="texture_view"
 android:layout_width="match_parent"
 android:layout_height="match_parent"/>

您需要确保启用了硬件加速,转到清单文件并添加此行

  • 在应用程序级别:<application android:hardwareAccelerated="true" ...>