使用ExoPlayer开发音乐应用时播放歌曲SeekBar不移动问题求助
问题排查与修复方案
- 问题1:Observer未正确注册
你代码中subscribeToObservers()方法在观察完currentlyPlayingSong后就提前闭合了,后续的playBackState、currentPlayerPosition、currentSongDuration三个LiveData观察者完全没有被注册到生命周期上,自然收不到任何更新通知。
修复方案:将三个观察者移到subscribeToObservers()方法内部,修正后代码如下:
private fun subscribeToObservers() { mainViewModel.currentlyPlayingSong.observe(viewLifecycleOwner) { if (it == null) return@observe currentPlayingSong = it.toSong() val formattedDuration = it.toSong()?.duration?.let { Utility.getSongDuration(true, it) } binding.txtSongDuration.text = formattedDuration } mainViewModel.playBackState.observe(viewLifecycleOwner) { playbackState = it binding.seekBar.progress = it?.currentPlaybackPosition?.toInt() ?: 0 } songViewModel.currentPlayerPosition.observe(viewLifecycleOwner){ if (shouldUpdateSeekBar){ binding.seekBar.progress = it.toInt() updatePlayingTime(it) } } songViewModel.currentSongDuration.observe(viewLifecycleOwner) { binding.seekBar.max = it.toInt() } }
- 问题2:
shouldUpdateSeekBar初始值错误
该变量默认值需要设置为true,仅在用户拖动SeekBar的onStartTrackingTouch回调中临时设为false,避免拖动过程中进度更新和用户操作冲突,松手后恢复为true。如果初始值为false,正常播放状态下进度永远不会更新。
修复方案:在Fragment中声明变量时初始化:
private var shouldUpdateSeekBar = true
问题3:PlaybackState取值字段错误
你在mainViewModel.playBackState的观察者中使用it?.position取值,和ViewModel中统一的currentPlaybackPosition字段不一致,会导致取不到正确的播放位置,上文修复代码已经同步修正了这个字段。问题4:ViewModel轮询逻辑优化
当前的死循环轮询没有空保护,也没有判断播放状态,会造成不必要的资源消耗,还可能出现空指针崩溃。优化后的更新逻辑如下:
private fun updateCurrentPlayerPosition() { viewModelScope.launch { while (true){ val position = playBackState.value?.currentPlaybackPosition // 只有播放状态为正在播放、且位置有变化时才更新 if (playBackState.value?.isPlaying == true && currentPlayerPosition.value != position) { position?.let { pos -> _currentPlayerPosition.postValue(pos) _currentSongDuration.postValue(MusicService.curSongDuration) } } delay(UPDATE_PLAYER_POSITION_INTERVAL) // 建议取值为1000ms以内,比如500ms } } }
内容的提问来源于stack exchange,提问作者Ibccx
相关产品推荐
相关产品推荐

