我正在尝试使用ExoPlayer 2流mp3文件。但是,初始加载时间太长。但是有时它会在1-2秒内开始播放同一文件,但有时会卡住10-20秒。
也许我对流进行了错误的初始化?
这是我的AudioPlayer类:
class AudioPlayer {
private static final DefaultBandwidthMeter BANDWIDTH_METER = new DefaultBandwidthMeter();
private Context mContext;
private SimpleExoPlayer mPlayer;
private String extraData;
private int state;
private ExoPlayer.EventListener mEventListener;
private ExtractorsFactory extractorsFactory;
private boolean shouldAutoPlay;
private DataSource.Factory mediaDataSourceFactory;
public SimpleExoPlayer getPlayer() {
return mPlayer;
}
AudioPlayer(Context context, ExoPlayer.EventListener eventListener){
shouldAutoPlay = true;
mEventListener = eventListener;
mContext = context;
state = 0;
mediaDataSourceFactory = buildDataSourceFactory(true);
extractorsFactory = new DefaultExtractorsFactory();
initializePlayer();
}
void play(String url){
extraData = url;
state = 1;
setMediaSource(url);
}
private void setMediaSource(String audioUrl) {
MediaSource mediaSource = new ExtractorMediaSource(Uri.parse(audioUrl),
mediaDataSourceFactory, extractorsFactory, null, null);
mPlayer.prepare(mediaSource, true, true);
}
boolean isPaused() {
return state == 2;
}
void setState(int state) {
this.state = state;
}
void pause() {
state = 2;
mPlayer.setPlayWhenReady(false);
}
void play() {
state = 1;
mPlayer.setPlayWhenReady(true);
}
void release(){
mPlayer.release();
}
private void initializePlayer() {
if (mPlayer == null) {
TrackSelection.Factory videoTrackSelectionFactory =
new AdaptiveVideoTrackSelection.Factory(BANDWIDTH_METER);
DefaultTrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
mPlayer = ExoPlayerFactory.newSimpleInstance(mContext, trackSelector, new DefaultLoadControl(),
null);
mPlayer.addListener(mEventListener);
EventLogger eventLogger = new EventLogger(trackSelector);
mPlayer.addListener(eventLogger);
mPlayer.setAudioDebugListener(eventLogger);
mPlayer.setMetadataOutput(eventLogger);
mPlayer.setPlayWhenReady(shouldAutoPlay);
}
}
private DataSource.Factory buildDataSourceFactory(boolean useBandwidthMeter) {
return ((SEApplication) mContext.getApplicationContext())
.buildDataSourceFactory(useBandwidthMeter ? BANDWIDTH_METER : null);
}
public long getDuration() {
return mPlayer.getDuration();
}
}
最佳答案
尝试以下操作:添加负载控制似乎可以解决此问题。
private void initializePlayer() {
if (mPlayer == null) {
TrackSelection.Factory videoTrackSelectionFactory =
new AdaptiveVideoTrackSelection.Factory(BANDWIDTH_METER);
DefaultTrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
LoadControl loadControl = new DefaultLoadControl();
loadControl.shouldStartPlayback(0, false);
mPlayer = ExoPlayerFactory.newSimpleInstance(mContext, trackSelector, loadControl,
null);
mPlayer.addListener(mEventListener);
}
}