如何在android中实现Exoplayer 2.11.1?

hiz5n14c  于 2023-09-28  发布在  Android
关注(0)|答案(5)|浏览(190)

我正在尝试实现exoplayer这是我的exoplayer版本

implementation 'com.google.android.exoplayer:exoplayer:2.11.1'

我正在创建一个音乐播放器应用程序,我不知道任何关于exoplayer我试图实现exoplayer从过去2天,但它不工作.官方文件里的东西我一点也看不懂。
我找到了很多例子和教程,但都是关于使用exoplayer播放视频。很多例子都使用了过时的方法。
我尝试使用这个tutorial来实现,但是很多方法都被弃用了,所以它不能正常工作。

simpleExoplayer = ExoPlayerFactory.newSimpleInstance(
            DefaultRenderersFactory(this),
            DefaultTrackSelector(adaptiveTrackSelectionFactory),
            DefaultLoadControl()
        )

任何人都可以建议我从哪里开始,或者我如何使用最新版本的exoplayer构建音乐流媒体应用程序。
如有任何帮助,我们将不胜感激。

j9per5c4

j9per5c41#

通过新的更新,您可以使用SimpleExoPlayer.Builder创建一个简单的播放器示例:

simpleExoplayer = SimpleExoPlayer.Builder(context).build()

您还可以为Builder提供不同的参数。参见https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/SimpleExoPlayer.Builder.html
您可以使用我创建的这个简单的自定义类来帮助您入门。

class ExoPlayerHelper(
    private val playerView: PlayerView,
    onError: (ExoPlaybackException) -> Unit,
    onPlayerBuffer: (Boolean) -> Unit
) {

    private var exoPlayer: ExoPlayer? = null
    private var mediaSource: ProgressiveMediaSource? = null

    private val playerListener = object : Player.EventListener {
        override fun onPlayerError(error: ExoPlaybackException) {
            super.onPlayerError(error)
            onError(error)
        }

        override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
            super.onPlayerStateChanged(playWhenReady, playbackState)
            onPlayerBuffer(playbackState == Player.STATE_BUFFERING)
        }
    }

    fun initializePlayer(url: String) {
        exoPlayer = SimpleExoPlayer.Builder(playerView.context).build()
        exoPlayer!!.repeatMode = Player.REPEAT_MODE_ALL
        exoPlayer!!.addListener(playerListener)

        playerView.player = exoPlayer

        val userAgent =
            Util.getUserAgent(playerView.context, playerView.context.getString(R.string.app_name))
        mediaSource = ProgressiveMediaSource
            .Factory(
                DefaultDataSourceFactory(playerView.context, userAgent),
                DefaultExtractorsFactory()
            )
            .createMediaSource(Uri.parse(url))

        exoPlayer!!.prepare(mediaSource!!, true, false)
        exoPlayer!!.playWhenReady = true
    }

    private fun killPlayer() {
        if (exoPlayer != null) {
            exoPlayer!!.release()
            exoPlayer = null
            mediaSource = null
            playerView.player = null
        }
    }
}
6qqygrtg

6qqygrtg2#

我也面临这个问题,这是我的解决方案

Declaration

private val exoPlayer: SimpleExoPlayer by lazy { SimpleExoPlayer.Builder(this).build()}

播放歌曲

private fun prepareExoPlayerFromURL(url: String) {
        val dataSourceFactory =
            DefaultDataSourceFactory(this, Util.getUserAgent(this, resources.getString(R.string.app_name)), null)
        val extractorsFactory = DefaultExtractorsFactory()
//        val audioSource = ExtractorMediaSource(uri, dataSourceFactory, extractorsFactory, null, null)

        val concateMediaSource = ConcatenatingMediaSource()

        // to play from song list
        for (i in mSongList) {      // song list song arraylist
            val mediaSource = ProgressiveMediaSource
                .Factory(
                    DefaultDataSourceFactory(this, dataSourceFactory),
                    DefaultExtractorsFactory()
                )
                .createMediaSource(Uri.parse(i.musicFile)/*Uri.parse(i.uri)*/)
            concateMediaSource.addMediaSource(mediaSource)
        }

        // to play single song
       /* val audioSource = ProgressiveMediaSource
            .Factory(
                DefaultDataSourceFactory(this, dataSourceFactory),
                DefaultExtractorsFactory()
            )
            .createMediaSource(Uri.parse(url))*/

        exoPlayer.prepare(concateMediaSource/*audioSource*/)
        exoPlayer.seekToDefaultPosition(songPosition)
        exoPlayer.playWhenReady = true

        setNotification()
    }

设置播放器和通知的**监听器

private fun setListoner() {
        exoPlayer.addListener(object : Player.EventListener {
            override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
                when (playbackState) {
                    Player.STATE_BUFFERING -> Log.e(TAG,"STATE_BUFFERING")
                    Player.STATE_ENDED -> Log.e(TAG,"STATE_ENDED")
                    Player.STATE_IDLE -> Log.e(TAG,"STATE_IDLE")
                    Player.STATE_READY ->{
                        if (playWhenReady) {
                            Log.e(TAG, "PlaybackStatus.PLAYING")
                        } else {
                            Log.e(TAG, "PlaybackStatus.PAUSED")
                        }
                    }
                    else -> Log.e(TAG,"PlaybackStatus.IDLE")
                }
            }
        })
    }

杀死玩家

private fun onDestroy() {
        if (exoPlayer != null) {
            exoPlayer.release()
            exoPlayer = null
            mediaSource = null
        }
    }

有关更多详细信息,请参见official documentation
Universal Music Player使用ExoPlayer进行本地音频播放。
Building feature-rich media apps with ExoPlayer (Google I/O '18)

l5tcr1uw

l5tcr1uw3#

For Java Guys(Java万岁)

活动中

private PlayerView epPlayerView = findViewById(R.id.design_reference);

公共功能

public static void runExoPlayer(PlayerView epPlayerView,
                                String url,
                                Context context) {

    Uri videoUri = Uri.parse(url);

    SimpleExoPlayer  exoPlayer = new SimpleExoPlayer.Builder(context).build();
    epPlayerView.setPlayer(exoPlayer);

    MediaItem mediaItem = MediaItem.fromUri(videoUri);
    exoPlayer.clearMediaItems();
    exoPlayer.setMediaItem(mediaItem);
    exoPlayer.prepare();
    exoPlayer.setPlayWhenReady(true);

}

构建Gradle

// Exo Media Player
    implementation 'com.google.android.exoplayer:exoplayer:2.15.1'
    implementation 'com.google.android.exoplayer:exoplayer-core:2.15.1'
    implementation 'com.google.android.exoplayer:exoplayer-ui:2.15.1'
    implementation 'com.google.android.exoplayer:exoplayer-dash:2.15.1'
    implementation 'com.google.android.exoplayer:exoplayer-hls:2.15.1'
    implementation 'com.google.android.exoplayer:exoplayer-smoothstreaming:2.15.1'
    androidTestImplementation 'androidx.test:rules:1.4.0'
fafcakar

fafcakar4#

在2.15.0版本之前,您可以按以下方式创建SimpleExoPlayer示例:

SimpleExoPlayer.Builder(this)
            .setMediaSourceFactory(mediaSourceFactory)
            .build()

在2.16.0版本中,不推荐使用SimpleExoPlayer,您应该改用ExoPlayer示例。可以按以下方式创建:

ExoPlayer.Builder(this)
            .setMediaSourceFactory(mediaSourceFactory)
            .build()

https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/SimpleExoPlayer.Builder.html

guykilcj

guykilcj5#

1.调用此方法:

private void initializePlayer() {
         FloatingWidgetService.hidePipPlayer();

         binding.videoOverlay.setVisibility(View.GONE);
         liveTvexoPlayer = new SimpleExoPlayer.Builder(context).build();
         binding.playerView.setPlayer(liveTvexoPlayer);
         binding.playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT);
         binding.playerView.setUseController(true);

         liveTvexoPlayer.setPlayWhenReady(true);
         liveTvexoPlayer.seekTo(0);
         appManageInterface.setLiveTvVideo(playBackUrl, "getReady", 0);
         Prefs.getPrefInstance().setValue(context, Const.VIDEO_URL, playBackUrl);

         imgViewChangeScreenOrientation = binding.playerView.findViewById(R.id.exo_fullscreen_icon);
         imgViewChangeScreenOrientation.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 liveTvexoPlayer.setPlayWhenReady(false);
                 liveTvexoPlayer.release();
                 Intent serviceIntent = new Intent(context, FloatingWidgetService.class);
                 serviceIntent.putExtra("videoUri", playBackUrl);
                 serviceIntent.putExtra("isfrom", "livetv");
 //                serviceIntent.putExtra("videoUri", "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/SubaruOutbackOnStreetAndDirt.mp4");
                 getActivity().startService(serviceIntent);
             }
         });

         AudioAttributes audioAttributes = new AudioAttributes.Builder()
                 .setUsage(C.USAGE_MEDIA)
                 .setContentType(C.CONTENT_TYPE_MOVIE)
                 .build();
         if (liveTvexoPlayer.getAudioComponent() != null)
             liveTvexoPlayer.getAudioComponent().setAudioAttributes(audioAttributes, true);
         try {
             if (!playBackUrl.equals("")) {
                 DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(context, Util.getUserAgent(context, getResources().getString(R.string.app_name)));
                 MediaSource videoSource = new HlsMediaSource.Factory(dataSourceFactory).createMediaSource(Uri.parse(playBackUrl));
                 liveTvexoPlayer.prepare(videoSource, true, true);
             }
         } catch (Exception e) {

         }
         liveTvexoPlayer.addListener(new Player.EventListener() {
             @Override
             public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
             }

             @Override
             public void onPlayerError(ExoPlaybackException error) {
                 switch (error.type) {
                     case TYPE_SOURCE:
                         binding.videoOverlay.setVisibility(View.VISIBLE);
                         break;
                     case TYPE_RENDERER:
                     case TYPE_UNEXPECTED:
                         liveTvexoPlayer.retry();
                         break;
                     case TYPE_OUT_OF_MEMORY:
                     case TYPE_REMOTE:
                         AppUtil.show_Snackbar(context, binding.playerView, error.getMessage(), true);
                         break;
                 }
             }
         });
     }

1.使用以下方法管理exoplayer:

@Override
    public void onResume() {
        super.onResume();
        mTracker.setScreenName("Screen - " + "Live Tv");
        mTracker.send(new HitBuilders.ScreenViewBuilder().build());
        binding.playerView.onResume();
        if (liveTvexoPlayer != null)
            liveTvexoPlayer.setPlayWhenReady(true);
    }

    @Override
    public void onStart() {
        super.onStart();
        binding.playerView.onResume();
        if (liveTvexoPlayer != null)
            liveTvexoPlayer.setPlayWhenReady(true);
    }

    @Override
    public void onPause() {
        binding.playerView.onPause();
        if (liveTvexoPlayer != null) {
            liveTvexoPlayer.setPlayWhenReady(false);
        }
        super.onPause();
    }

    @Override
    public void onStop() {
        binding.playerView.onPause();
        if (liveTvexoPlayer != null)
            liveTvexoPlayer.setPlayWhenReady(false);
        super.onStop();
    }

    @Override
    public void onDestroy() {
        binding.playerView.onPause();
        if (liveTvexoPlayer != null) {
            liveTvexoPlayer.release();
            liveTvexoPlayer = null;
        }
        super.onDestroy();
    }

相关问题