Android playing audio with Exoplayer 2 example

The Exoplayer is initialized with SimpleExoPlayer in the onCreate(), with DefaultRenderersFactory, DefaultTrackSelector, and DefaultLoadControl. The data source (audio) is initialized using ProgressiveMediaSource with DefaultDataSourceFactory and DefaultExtractorsFactory. The Exoplayey is prepared with this ProgressiveMediaSource. In the onResume(), the playWhenReady property of the Exoplayer is set to true, in the onPause(), the playWhenReady property of the Exoplayer is set to false, and in the onDestroy(), the player is released.

class MainActivity : AppCompatActivity(), Player.EventListener {

    lateinit var player: SimpleExoPlayer

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val renderersFactory = DefaultRenderersFactory(this)
        val trackSelectionFactory = AdaptiveTrackSelection.Factory()
        val trackSelectSelector = DefaultTrackSelector(trackSelectionFactory)
        val loadControl = DefaultLoadControl()

        player = ExoPlayerFactory.newSimpleInstance(this, renderersFactory, trackSelectSelector, loadControl)
        player.addListener(this)

        val dataSourceFactory = DefaultDataSourceFactory(this, getString(R.string.app_name))
        val extractorsFactory = DefaultExtractorsFactory()

        val mediaSource = ProgressiveMediaSource
            .Factory(dataSourceFactory, extractorsFactory)
            .createMediaSource(Uri.parse("https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_5MG.mp3"))

        player.prepare(mediaSource)

        video_view.player = player

    }

    override fun onResume() {
        super.onResume()
        player.playWhenReady = true
    }

    override fun onPause() {
        super.onPause()
        player.playWhenReady = false
    }

    override fun onDestroy() {
        super.onDestroy()
        player.release()
    }

    //region Player.EventListener
    override fun onTracksChanged(trackGroups: TrackGroupArray?, trackSelections: TrackSelectionArray?) {
    }

    override fun onLoadingChanged(isLoading: Boolean) {
    }

    override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
    }

    override fun onPlayerError(error: ExoPlaybackException?) {
    }

    override fun onPlaybackParametersChanged(playbackParameters: PlaybackParameters?) {
    }
    //endregion
}

activity_main.xml



    



view_player_controller.xml




    

        

        

    


Complete example in Github

Search within Codexpedia

Custom Search

Search the entire web

Custom Search