清理播放列表并添加新曲目后,如果尝试播放最后一个曲目,则会出现以下错误:
E/ExoPlayerImplInternal: Internal runtime error.
java.lang.ArrayIndexOutOfBoundsException: length=50; index=50
at com.google.android.exoplayer2.source.ConcatenatingMediaSource$ConcatenatedTimeline.getTimelineByChildIndex(ConcatenatingMediaSource.java:777)
at com.google.android.exoplayer2.source.AbstractConcatenatedTimeline.getNextWindowIndex(AbstractConcatenatedTimeline.java:66)
at com.google.android.exoplayer2.Timeline.getNextPeriodIndex(Timeline.java:670)
at com.google.android.exoplayer2.Timeline.isLastPeriod(Timeline.java:692)
at com.google.android.exoplayer2.MediaPeriodQueue.isLastInTimeline(MediaPeriodQueue.java:747)
at com.google.android.exoplayer2.MediaPeriodQueue.getMediaPeriodInfoForContent(MediaPeriodQueue.java:714)
at com.google.android.exoplayer2.MediaPeriodQueue.getMediaPeriodInfo(MediaPeriodQueue.java:672)
at com.google.android.exoplayer2.MediaPeriodQueue.getFirstMediaPeriodInfo(MediaPeriodQueue.java:500)
at com.google.android.exoplayer2.MediaPeriodQueue.getNextMediaPeriodInfo(MediaPeriodQueue.java:125)
at com.google.android.exoplayer2.ExoPlayerImplInternal.maybeUpdateLoadingPeriod(ExoPlayerImplInternal.java:1482)
at com.google.android.exoplayer2.ExoPlayerImplInternal.updatePeriods(ExoPlayerImplInternal.java:1367)
at com.google.android.exoplayer2.ExoPlayerImplInternal.doSomeWork(ExoPlayerImplInternal.java:495)
at com.google.android.exoplayer2.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:301)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
索引我的最后一个曲目是49,我调用函数seekTo(49, 0)
,但是如果我不清除播放列表并且不添加新曲目就可以了。
编写一些功能的代码:
override fun addMusicInPlaylist(listSong: List<Song>, removeOld: Boolean) {
val dataSource = DefaultHttpDataSourceFactory(Util.getUserAgent(this, getString(R.string.app_name))).createDataSource()
dataSource.setRequestProperty("Referer", "http://example.com/")
val factory = DataSource.Factory { dataSource }
val listMediaSources = ArrayList<MediaSource>()
listSong.forEachWithIndex { i, it->
listMediaSources.add(SongMediaSource(ExtractorMediaSource.Factory(factory).createMediaSource(Uri.parse(it.url)),it))
}
if (removeOld) {
exoPlayer.playWhenReady = false
mediaSources.clear {
mediaSources.addMediaSources(listMediaSources)
}
} else
mediaSources.addMediaSources(listMediaSources)
}
override fun changeSong(song: Song, position: Int) {
if (songId == song.songId)
exoPlayer.playWhenReady = !exoPlayer.playWhenReady
else {
songId = song.songId
exoPlayer.seekTo(position, C.TIME_UNSET)
exoPlayer.playWhenReady = true
}
}