📜  android exoplayer play pause mp3 (1)

📅  最后修改于: 2023-12-03 14:39:07.741000             🧑  作者: Mango

Android ExoPlayer Play Pause MP3

ExoPlayer is an open source media player developed by Google. It provides a powerful and flexible interface for playing audio and video files in Android apps. In this tutorial, we will learn how to use ExoPlayer to play and pause MP3 files in an Android app.

Prerequisites
  • Android Studio 4.1 or higher
  • Android API level 21 or higher
  • Kotlin 1.4.10 or higher
Step 1: Add ExoPlayer dependency

Add the following dependency to your app's build.gradle file:

implementation 'com.google.android.exoplayer:exoplayer-core:2.13.3'
Step 2: Create ExoPlayer instance

Create an instance of SimpleExoPlayer in your activity or fragment:

private lateinit var exoPlayer: SimpleExoPlayer

private fun initializePlayer() {
    exoPlayer = SimpleExoPlayer.Builder(context).build()
    playerView.player = exoPlayer
}

To release the player, call:

exoPlayer.release()
Step 3: Create MediaSource

Create a MediaSource instance from a media file:

private fun buildMediaSource(uri: Uri): MediaSource {
    val dataSourceFactory = DefaultDataSourceFactory(context, "exoplayer-sample")
    return ProgressiveMediaSource.Factory(dataSourceFactory)
            .createMediaSource(uri)
}

In this example, we are creating a ProgressiveMediaSource from a URI.

Step 4: Prepare the player

Prepare the player with the MediaSource created in the previous step:

private fun preparePlayer(uri: Uri) {
    val mediaSource = buildMediaSource(uri)
    exoPlayer.prepare(mediaSource)
    exoPlayer.playWhenReady = true
}

In this example, we are playing the media file as soon as ExoPlayer is ready.

Step 5: Play and pause the player

To play or pause the player, call:

exoPlayer.playWhenReady = true  // To play the media file
exoPlayer.playWhenReady = false // To pause the media file
Conclusion

In this tutorial, we have learned how to use ExoPlayer to play and pause MP3 files in an Android app. ExoPlayer is a powerful and flexible media player that provides a great user experience.