Exoplayer的DynamicConcatenatingMediaSource无效

时间:2017-10-28 01:43:55

标签: android android-studio exoplayer exoplayer2.x

我正在实施一个音乐应用程序。我正在使用Exoplayer2

我正在尝试使用DynamicConcatenatingMediaSource添加&将项目动态删除到播放列表。

这是我的实施。

public void initMusicPlayer(){

        if (songs !=null)
        {

            MediaSource mediaSource;
            ArrayList<MediaSource> sources = new ArrayList<>();

            MusicItem song;
            for (int i=0;i< songs.size();i++)
            {
                song = songs.get(i);
                mediaSource = buildMediaSource(Uri.parse(song.getMusicUrl()));
                sources.add(mediaSource);
            }

            dynamicMediaSource = new DynamicConcatenatingMediaSource();
            dynamicMediaSource.addMediaSources(sources);
            exoPlayer.prepare(dynamicMediaSource,false,false);

            exoPlayer.addListener(this);
            if (currentPlayingSongIndex == -1)
            {
                exoPlayer.setPlayWhenReady(false);
            }
            else
            {
                exoPlayer.seekTo(currentPlayingSongIndex,0);
                exoPlayer.setPlayWhenReady(true);
            }
        }
    }

public void addItemToPlaylist(MusicItem song,boolean shouldPlay){

        long position = exoPlayer.getContentPosition();
        MediaSource mediaSource = buildMediaSource(Uri.parse(song.getMusicUrl()));
        dynamicMediaSource.addMediaSource(mediaSource);
        exoPlayer.prepare(dynamicMediaSource,false,false);

        if (shouldPlay)
        {
            exoPlayer.seekTo(currentPlayingSongIndex,0);
        }
        else
        {
            exoPlayer.seekTo(currentPlayingSongIndex,position);
        }
    }

但是,这种实现不起作用。它没有发挥任何作用。

上述代码有什么问题?

另外,如何动态地将项目添加到播放列表?以上addItemToPlaylist会起作用吗?

1 个答案:

答案 0 :(得分:0)

这是我在Kotlin播放mp3文件播放列表时创建的功能。 (您可以将其粘贴到Android Studio中,如果使用Java,则会将其转换为Java)

private fun mediaPlayerConfiguration() {
    val bandwidthMeter = DefaultBandwidthMeter()
    val extractorsFactory = DefaultExtractorsFactory()
    val trackSelectionFactory = AdaptiveTrackSelection.Factory(bandwidthMeter)
    val trackSelector = DefaultTrackSelector(trackSelectionFactory)
    val defaultBandwidthMeter = DefaultBandwidthMeter()
    val dataSourceFactory = DefaultDataSourceFactory(this,
            Util.getUserAgent(this, "mediaPlayerSample"), defaultBandwidthMeter)

    val dynamicConcatenatingMediaSource = DynamicConcatenatingMediaSource()

    for (item in myActivity.list) {
        var mediaSource = ExtractorMediaSource.Factory(dataSourceFactory).setExtractorsFactory(extractorsFactory).createMediaSource(Uri.parse(item))
        dynamicConcatenatingMediaSource.addMediaSource(mediaSource)
    }

    mPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector)
    mPlayer.prepare(dynamicConcatenatingMediaSource)

    mPlayer.playWhenReady = true
}