Jetpack Compose中Exoplayer playWhenReady失效 无法自动播放背景视频问题问询
修复Jetpack Compose ExoPlayer背景视频无法自动播放方案
原有代码无法自动播放的核心原因有两个:
- 未主动调用ExoPlayer的
prepare()方法,播放器没有完成媒体资源加载流程,playWhenReady自然不会触发播放 - 播放逻辑没有绑定Compose页面生命周期,页面退后台再返回时也容易出现播放中断问题
修复后的完整可运行代码如下:
@Composable fun VideoPlayer() { val context = LocalContext.current // 绑定页面生命周期,避免后台无效播放耗电 val lifecycleOwner = LocalLifecycleOwner.current val exoPlayer = remember { SimpleExoPlayer.Builder(context) .build().apply { val dataSourceFactory: DataSource.Factory = DefaultDataSourceFactory( context, Util.getUserAgent(context, context.packageName) ) val source = ProgressiveMediaSource.Factory(dataSourceFactory) .createMediaSource( MediaItem.Builder().setUri( Uri.parse("file:///android_asset/intro_video_android_19_9.mp4") ).build() ) this.repeatMode = Player.REPEAT_MODE_ALL this.setMediaSource(source) // 提前设置自动播放开关,资源准备完成后会自动启动播放 this.playWhenReady = true // 主动触发媒体资源加载,缺失这步会一直停留在黑屏待加载状态 this.prepare() } } // 生命周期监听,页面可见时播放、不可见时暂停,销毁时释放资源 DisposableEffect(lifecycleOwner) { val observer = LifecycleEventObserver { _, event -> when (event) { Lifecycle.Event.ON_RESUME -> exoPlayer.play() Lifecycle.Event.ON_PAUSE -> exoPlayer.pause() Lifecycle.Event.ON_DESTROY -> exoPlayer.release() else -> {} } } lifecycleOwner.lifecycle.addObserver(observer) onDispose { lifecycleOwner.lifecycle.removeObserver(observer) exoPlayer.release() } } AndroidView( factory = { localContext -> PlayerView(localContext).apply { player = exoPlayer // 完全关闭控制器,避免触控操作影响背景播放 useController = false resizeMode = AspectRatioFrameLayout.RESIZE_MODE_ZOOM } } ) }
额外注意点
- 若应用targetSdk >= 31,需要在清单文件中申请
android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK权限,否则后台切回时可能出现播放异常 - 本地asset视频建议提前压缩,避免首次加载时黑屏时间过长
- 若需要使用透明背景视频,可在PlayerView初始化时补充
setShutterBackgroundColor(Color.TRANSPARENT)配置
内容的提问来源于stack exchange,提问作者Fabiel Casas
相关产品推荐
相关产品推荐

