Android:ExoPlayer - 流式mp3

时间:2017-02-15 08:48:10

标签: android audio-streaming exoplayer

我正在尝试使用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();
}
}

0 个答案:

没有答案