📅  最后修改于: 2023-12-03 14:39:07.741000             🧑  作者: Mango
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.
Add the following dependency to your app's build.gradle
file:
implementation 'com.google.android.exoplayer:exoplayer-core:2.13.3'
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()
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.
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.
To play or pause the player, call:
exoPlayer.playWhenReady = true // To play the media file
exoPlayer.playWhenReady = false // To pause the media file
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.