You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在根视图为PlayerView的Media3 ExoPlayer中实现截图?

ExoPlayer PlayerView 截图实现方案

核心思路

ExoPlayer的PlayerView默认用SurfaceView渲染视频,也可配置为TextureView。两种视图的截图方式不同,优先推荐用TextureView简化实现。


1. 配置PlayerView使用TextureView(可选但推荐)

在布局文件中指定Surface类型为TextureView,规避SurfaceView在低版本系统的截图限制:

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

2. 实现截图逻辑

针对TextureView的截图

直接从TextureView获取视频帧Bitmap:

PlayerView playerView = findViewById(R.id.playerView);
View videoSurface = playerView.getVideoSurfaceView();

if (videoSurface instanceof TextureView) {
    TextureView textureView = (TextureView) videoSurface;
    Bitmap screenshot = textureView.getBitmap();
    // 处理截图(保存或展示)
    saveScreenshot(screenshot);
}

针对SurfaceView的截图(Android 8.0+)

SurfaceView无法直接获取画面,需使用PixelCopy API实现:

if (videoSurface instanceof SurfaceView && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    SurfaceView surfaceView = (SurfaceView) videoSurface;
    Surface surface = surfaceView.getHolder().getSurface();
    Bitmap screenshot = Bitmap.createBitmap(
        surfaceView.getWidth(), 
        surfaceView.getHeight(), 
        Bitmap.Config.ARGB_8888
    );

    PixelCopy.request(surface, screenshot, copyResult -> {
        if (copyResult == PixelCopy.SUCCESS) {
            saveScreenshot(screenshot);
        } else {
            // 截图失败,可添加错误提示
        }
    }, Handler.getMainLooper());
}

3. 保存截图到本地示例

private void saveScreenshot(Bitmap bitmap) {
    File screenshotFile = new File(
        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
        "exo_player_screenshot_" + System.currentTimeMillis() + ".jpg"
    );

    try (FileOutputStream fos = new FileOutputStream(screenshotFile)) {
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
        fos.flush();
        // 通知系统图库更新
        MediaScannerConnection.scanFile(
            this, 
            new String[]{screenshotFile.getAbsolutePath()}, 
            null, 
            null
        );
    } catch (IOException e) {
        e.printStackTrace();
    }
}

注意事项

  • Android 6.0及以上需动态申请WRITE_EXTERNAL_STORAGE权限(Android 10+可改用MediaStore API避免权限申请)
  • Android 8.0以下SurfaceView截图实现复杂,建议直接切换为TextureView

内容的提问来源于stack exchange,提问作者Тимфоей Сорокин

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 02:52:39