With Media3's ExoPlayer, how do you play a lesson's HLS video in a PlayerView, and when and why must you release the player?
answer
- builder, item, prepare, play
- one format module per stream type
- a single application thread
- tie creation and release to onStart and onStop
- decoders are shared with other apps
basics
~20 sBuild an ExoPlayer with ExoPlayer.Builder, set it on a PlayerView, give it a MediaItem for the .m3u8 URI (needs the HLS module), then prepare() and play(). Release it when the screen stops: it holds decoders other apps need.
solid answer
~40 sI add `media3-exoplayer`, `media3-ui` and `media3-exoplayer-hls`, build the player with `ExoPlayer.Builder(context).build()` and attach it with `playerView.player = player`. I pass `MediaItem.fromUri(lessonUri)` to `setMediaItem`, call `prepare()` so it leaves `STATE_IDLE` and starts loading, and call `play()`, which only sets `playWhenReady`, so playback starts once the player reaches `STATE_READY`. Every call goes through one application thread, normally main, or ExoPlayer throws "Player is accessed on the wrong thread". Because the player holds video decoders, buffers and loader threads, I create it in `onStart` and call `release()` in `onStop` on API 24 and later, saving the position first; a released player cannot be reused. Unlike the platform `MediaPlayer`, ExoPlayer ships inside the app, so its HLS support does not depend on the device's Android version.
code
kotlin · 38 linesimport android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.media3.common.MediaItem
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
class LessonActivity : AppCompatActivity() {
private lateinit var playerView: PlayerView
private var player: ExoPlayer? = null
private var resumePositionMs = 0L
private val lessonUri = "https://cdn.example.com/lessons/42/master.m3u8"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_lesson)
playerView = findViewById(R.id.player_view)
}
override fun onStart() {
super.onStart()
val exoPlayer = ExoPlayer.Builder(this).build()
playerView.player = exoPlayer
exoPlayer.setMediaItem(MediaItem.fromUri(lessonUri), resumePositionMs)
exoPlayer.prepare()
exoPlayer.play()
player = exoPlayer
}
override fun onStop() {
super.onStop()
player?.let {
resumePositionMs = it.currentPosition
it.release()
}
player = null
playerView.player = null
}
}go deeper
Recall the five steps in order: build, attach to PlayerView, setMediaItem, prepare, play. Then name release() and the lifecycle callback where you call it.
Explain what prepare() and play() each change, why play() is safe before STATE_READY, and why the HLS module is a separate dependency the player loads by reflection.
Show you have debugged player leaks: decoders held by unreleased instances, wrong-thread exceptions, and restoring position and playlist index after an onStop release.
Frame the player's lifetime as a resource policy for the team: who owns each instance, when it is released, and how screens hand playback over without leaking decoders.
## What ExoPlayer is **ExoPlayer** is the default implementation of Media3's `Player` interface: the object that loads media, decodes it and renders audio and video. It is a library compiled into the app, not part of the operating system. That is the short answer to why apps use it instead of the platform `MediaPlayer`: the platform player's behaviour and format support vary with the device's Android version, while ExoPlayer's HLS and DASH support, bug fixes and extension points (data sources, track selection, buffering policy) ship with the app and behave the same on every device the app supports. In the language-learning app, each lesson is a short video served over **HLS**, an `.m3u8` playlist that points at media segments in several qualities. ## The dependencies - `androidx.media3:media3-exoplayer` is the player itself. - `androidx.media3:media3-exoplayer-hls` adds HLS. ExoPlayer's default media source factory loads the HLS source by reflection, so without this module `setMediaItem` fails with an `IllegalStateException` whose cause is a `ClassNotFoundException`. - `androidx.media3:media3-ui` provides `PlayerView` for View-based layouts. - Every Media3 module must use the **same version**; this answer assumes 1.11.1. ## Building, attaching and starting 1. **Build**: `ExoPlayer.Builder(context).build()`. The builder takes options such as audio attributes, a wake mode or a custom media source factory. `build()` may be called once; a second call throws `IllegalStateException`. 2. **Attach**: `playerView.player = player`. `PlayerView` renders video and subtitles and shows playback controls; setting `null` detaches the player. 3. **Describe the media**: `player.setMediaItem(MediaItem.fromUri(lessonUri))`. The player infers HLS from the `.m3u8` extension. If the URL has no such extension, build the item with `MediaItem.Builder().setUri(uri).setMimeType(MimeTypes.APPLICATION_M3U8)`. 4. **Prepare**: `prepare()` moves the player out of `STATE_IDLE`; it starts loading the playlist and acquires decoders. 5. **Play**: `play()` is the same as `setPlayWhenReady(true)`. It is safe to call before the player is ready: playback starts as soon as the state becomes `STATE_READY`. ```kotlin val player = ExoPlayer.Builder(context).build() playerView.player = player player.setMediaItem(MediaItem.fromUri(lessonUri)) player.prepare() player.play() ``` ## Controlling a lesson Once the player is prepared, the learner's actions map onto `Player` methods, and a `PlayerView` calls the same methods from its built-in controls: - `pause()` and `play()` toggle `playWhenReady`; the position is kept. - `seekBack()` and `seekForward()` jump by the builder's increments, 5 and 15 seconds by default; `ExoPlayer.Builder.setSeekBackIncrementMs(3_000)` suits a "replay the last sentence" button. - `setPlaybackSpeed(0.75f)` slows the narration for a beginner without lowering its pitch. - `seekTo(positionMs)` jumps to a point in the lesson, such as the start of an exercise. ## The application thread An ExoPlayer instance must be accessed from **one application thread**. By default that is the thread whose `Looper` built the player, or the main thread when the building thread has no `Looper`; `Player.getApplicationLooper()` reports it. The main thread is required when you use Media3's UI components. A call from another thread throws `IllegalStateException` with the message "Player is accessed on the wrong thread". Listener callbacks arrive on that same thread. The heavy work, loading segments and feeding decoders, runs on ExoPlayer's internal playback thread, which is why the main thread stays responsive. ## Releasing the player A player holds scarce resources: hardware video decoders, audio output, memory buffers and loader threads. The `Player` contract says `release()` must be called when the player is no longer required, and the player must not be used afterwards. - **When**: on API 24 and later, create the player in `onStart` and release it in `onStop`, because in multi-window mode an activity can stay visible while paused. On API 23 and lower, use `onResume` and `onPause`. - **Keep the place**: read `currentPosition` and `currentMediaItemIndex` before releasing, and restore them with `setMediaItem(item, positionMs)` when you build the next player. - **Detach the view**: set `playerView.player = null`, so the view does not keep a reference to a released player. - **`stop()` is different**: it drops the loaded media but keeps the instance usable, so a later `prepare()` works. It does not replace `release()`. - **What a leak costs**: an unreleased player keeps its decoder, so the next screen, or another app, can fail to initialise a decoder of its own, and the leaked instance keeps its buffers in memory. ## Compose instead of Views Compose apps use the Compose UI modules instead of `PlayerView`. `media3-ui-compose` provides `PlayerSurface` (since 1.6.0) and `ContentFrame` for building your own controls; `media3-ui-compose-material3` provides the `Player` composable (since 1.10.0), which combines the video surface with Material 3 controls. The player's lifetime still follows the screen's lifecycle rather than composition: build it when the screen starts and release it when the screen stops.
- Why does a leaked ExoPlayer hurt other apps and not only yours?Hardware video decoders are a limited, device-wide resource. An unreleased player keeps its decoder instance and buffers, so the next screen, or another app, can fail to initialise a decoder and report a decoder error instead of playing. Releasing in `onStop` returns the decoder as soon as the lesson leaves the screen.
- What changes if the lesson URL does not end in .m3u8?ExoPlayer infers the stream type from the URI's extension and the item's MIME type. Without either hint it treats the URL as a progressive file and fails to recognise the format. Build the item with `MediaItem.Builder().setUri(uri).setMimeType(MimeTypes.APPLICATION_M3U8)` so the HLS source is used.
- How do you show the same player in a Jetpack Compose screen?Use `PlayerSurface` from `media3-ui-compose` (since 1.6.0) and draw your own controls, or the `Player` composable from `media3-ui-compose-material3` (since 1.10.0), which bundles the surface with Material 3 controls. The ExoPlayer is still built and released with the screen's lifecycle.
A rental car from a small depot: you pick it up when the trip starts and return it when you park for good, because the next customer cannot drive a car you are still holding, even if it sits unused in your driveway.
- ExoPlayer is built into Android, so its supported formats depend on the OS version.
- play() throws unless the player has already reached STATE_READY.
- stop() frees the player for good, so release() is never needed.
- PlayerView releases its player automatically when the activity is destroyed.
- Any background thread may call ExoPlayer methods safely.
- HLS plays with media3-exoplayer alone; the format modules are optional extras.
Assumes Media3 1.11; PlayerSurface arrived in media3-ui-compose in 1.6.0 and the Material 3 Player composable in 1.10.0.