我在我的项目中实现了DynamicConcatenatingMediaSource并且遇到了一个错误,在方法exoPlayer.prepare(source);
中,在调用exoPlayer.seekTo(currentPosition, C.TIME_UNSET);
之前,歌曲开始在播放列表的开头播放。
所以这会导致我的应用程序出现UI错误。
对于已经缓存的歌曲,用户可以在转到下一首歌曲之前听到第一首歌曲。
private BroadcastReceiver playNewAudio = new BroadcastReceiver() {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onReceive(Context context, Intent intent) {
if (exoPlayer != null) {
try {
if (!exoPlayer.getPlayWhenReady()) {
resumeMedia();
sendBroadcast(Dispatcher.Broadcast.NEW_TRACK_PLAYING, "");
return;
}
} catch (Exception e) {
e.printStackTrace();
}
}
//Get the new media index form SharedPreferences
if (songManager.currentPosition != -1 && songManager.currentPosition < songManager.getCurrentPlayList().size()) {
//index is in a valid range
songManager.activeTrack = songManager.getCurrentPlayList().get(songManager.currentPosition);
//sendBroadcast(Dispatcher.Broadcast.NEW_TRACK_PLAYING,"");
if (songManager.getPreviousPlaylist().equals(songManager.currentPlayList))
seekToCurrent(songManager.currentPosition);
else
initExo();
} else {
stopSelf();
}
/*stopMedia();*/
if (exoPlayer != null) {
try {
exoPlayer.setPlayWhenReady(shouldAutoPlay);
} catch (Exception e) {
e.printStackTrace();
}
} else {
initExo();
}
/*initMediaPlayer();*/
updateMetaData();
buildNotification(PlaybackStatus.PLAYING);
}
};
private void initExo() {
songManager = SongManager.getInstance();
int currentPosition = songManager.getCurrentPosition();
window = new Timeline.Window();
defaultBandwidthMeter = new DefaultBandwidthMeter();
LoadControl loadControl = new DefaultLoadControl();
trackSelectionFactory = new AdaptiveTrackSelection.Factory(defaultBandwidthMeter);
trackSelector = new DefaultTrackSelector(trackSelectionFactory);
boolean newExo = exoPlayer == null;
if (newExo)
exoPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector, loadControl);
exoPlayer.addListener(this);
source = initMediaSource();
exoPlayer.prepare(source);
exoPlayer.seekTo(currentPosition, C.TIME_UNSET);
exoPlayer.setPlayWhenReady(true);
}
private DynamicConcatenatingMediaSource initMediaSource() {
clearSource();
DynamicConcatenatingMediaSource mediaSource = new DynamicConcatenatingMediaSource();
for (Track track : songManager.getCurrentPlayList()) {
if (track != null && !track.getSource().isEmpty()) {
HlsMediaSource source = new
HlsMediaSource(Uri.parse(track.getSource()), cacheDataSourceFactory(), 5, null, null);
mediaSource.addMediaSource(source);
} else {
Log.e("Bad_Track", track.toString());
}
}
songManager.setPreviousPlaylist(songManager.currentPlayList);
return mediaSource;
}
这在同一个播放列表中工作正常。
我能够找到这个问题,因为我在该行添加了断点,并在我离开onPrepared
方法时注意到音乐开始播放。