How to implement Exoplayer 2.11.1 in android?
Asked Answered
G

5

10

i am trying to implement exoplayer this is my exoplayer version

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

i am creating a music player app and i don't know anything about exoplayer i am trying to implement exoplayer from last 2 days but it's not working. i couldn't understand anything in the official documentation .

i find many example and tutorial but it's all about playing video using exoplayer. many example's are using deprecated methods.

I am trying to implement using this tutorial but many of methods are deprecated so it's not working EX.

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

can anyone suggest me where to start or how do i build music streaming app using latest version of exoplayer.

Any help would be highly appreciated.

Geomancy answered 21/12, 2019 at 20:29 Comment(0)
I
17

With the new update, you can create a simple player instance using SimpleExoPlayer.Builder:

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

You can also supply the Builder with different arguments. See https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/SimpleExoPlayer.Builder.html

You can use this simple custom class I created to help you get started.

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
        }
    }
}
Ilex answered 22/12, 2019 at 3:39 Comment(2)
what kind of language the sample is written with? is it dart or kotlin?Loseff
@Loseff it's kotlinSyllabub
F
5

I also faced this problem and this my solution

Declaration

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

Play Song

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()
    }

to set listener of player and notification

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")
                }
            }
        })
    }

to Kill player

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

for more detail you can see official documentation

The Universal Music Player uses ExoPlayer for local audio playback.

Building feature-rich media apps with ExoPlayer (Google I/O '18)

Fatherly answered 1/2, 2020 at 14:56 Comment(1)
thanks, it's working for me, and thanks for extra information and links.Geomancy
Z
4

For Java Guys (Long Live Java)

In Activity

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

The Public Function

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);

}

Build 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'
Zymolysis answered 19/10, 2021 at 7:6 Comment(0)
A
1

Until 2.15.0 version, you can create SimpleExoPlayer instance as the following :

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

With the 2.16.0 version, SimpleExoPlayer is deprecated, you should use ExoPlayer instance instead. You can create it as the following :

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

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

Austro answered 18/11, 2021 at 12:27 Comment(0)
S
0
  1. Call this method :

    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;
                     }
                 }
             });
         }
    
  2. Manage exoplayer with below method:

        @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();
        }
    
Sidonie answered 27/9, 2023 at 21:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.