Nucleus
Media player

VideoNew

Show a video with VideoPlayerSurface, build controls on VideoPlayerState, and add fullscreen, subtitles, picture-in-picture and thumbnails.

View as Markdown

VideoPlayerState is the player; VideoPlayerSurface shows it. The state lives as long as you remember it: a surface removed and added back (a list item recycled, a screen left and come back to) shows the same frame and playback goes on.

media-playermacOSWindowsLinuxAndroidiOSWebDesktop Gradle plugin: Not neededDesktop window runtime: Required

Create the player

val player = rememberVideoPlayerState()

Outside a composition, createVideoPlayerState() returns one you dispose() yourself. Both take an optional AudioMode (whether the player pauses, ducks or mixes with other apps' audio, on Android and iOS) and a CacheConfig (an on-disk cache of streamed media, Android and iOS).

Open a media

player.openUri("https://example.com/movie.mp4")             // plays when ready
player.openUri(uri, InitialPlayerState.PAUSE)               // shows frame 0, paused
player.openUri(uri, headers = mapOf("Authorization" to "Bearer …"))
player.openFile(platformFile)                               // a FileKit PlatformFile
player.openAsset("videos/intro.mp4")                        // Android assets, iOS bundle

An open sets isLoading, then hasMedia once the media is ready, with duration and metadata filled in. A paused open shows frame 0. Volume, speed and loop carry over from one media to the next.

Show it

VideoPlayerSurface(
    playerState = player,
    modifier = Modifier.fillMaxSize(),
    contentScale = ContentScale.Fit,
) {
    // Compose drawn over the video: your controls
    PlayerControls(player)
}

contentScale follows Compose's ContentScale (Fit, Crop, FillBounds…); the picture is clipped to the surface. The overlay is plain Compose, on every platform.

Build controls

@Composable
fun PlayerControls(player: VideoPlayerState) {
    Column {
        Slider(
            value = player.sliderPos,
            onValueChange = { player.seekStart(it) },   // moves the slider only
            onValueChangeFinished = { player.seekFinished() },
            valueRange = 0f..1000f,
        )
        Row {
            IconButton(onClick = { if (player.isPlaying) player.pause() else player.play() }) {
                Icon(if (player.isPlaying) Icons.Default.Pause else Icons.Default.PlayArrow, null)
            }
            Text("${player.positionText} / ${player.durationText}")
        }
    }
}
MemberWhat it does
play() / pause() / stop()stop() pauses and rewinds to 0, the media stays loaded
seekTo(value)value is a slider position, 0..1000 over the whole duration
seekStart(value) / seekFinished()A drag: the slider moves, the seek happens on release
currentTime / durationSeconds; positionText / durationText are formatted
volume0..1
playbackSpeedClamped to the supported range
loopRestarts at the end; onRestart runs on each wrap instead of onPlaybackEnded
onPlaybackEndedRuns once when the media ends without loop
metadataTitle, size (as displayed: rotation applied), frame rate, bitrate, MIME type, audio channels and sample rate; a field the platform cannot report stays null
error / clearError()SourceError, NetworkError, CodecError or UnknownError

Every call is safe from any thread and returns at once: isPlaying is true as soon as play() returns.

Go fullscreen

player.toggleFullscreen()   // or player.isFullscreen = true

On the desktop the video opens in a Nucleus window in real fullscreen; on Android and iOS it fills the screen; on the web it uses the browser's fullscreen, and Esc turns isFullscreen off.

Add subtitles

External SRT and WebVTT files, drawn by Compose over the video:

player.selectSubtitleTrack(
    SubtitleTrack(label = "English", language = "en", src = "https://example.com/movie.en.vtt"),
)
player.subtitleTextStyle = TextStyle(color = Color.White, fontSize = 18.sp)
player.subtitleBackgroundColor = Color.Black.copy(alpha = 0.6f)
player.disableSubtitles()

Subtitles carried by a stream (HLS, DASH) are tracks: see Streaming.

Picture-in-picture

On Android and iOS:

player.isPipEnabled = true          // Android: enters PiP when the user leaves the app
val result = player.enterPip()      // Success, NotSupported, NotEnabled or NotPossible

isPipSupported says whether the platform has it, isPipActive whether the player is in it. On Android, declare android:supportsPictureInPicture="true" on the activity.

Thumbnails

loadVideoThumbnail decodes the frame containing a position, apart from any player, for seek-bar previews or chapter pictures:

val preview: ImageBitmap? = loadVideoThumbnail(
    uri = "https://example.com/movie.mp4",
    positionMs = 42_000,
    maxSize = 160,                       // longer side, aspect ratio kept
)

It returns the same frame a paused player would show there. Android uses MediaMetadataRetriever, Windows a Media Foundation source reader of its own, Linux a GStreamer pipeline of its own, macOS and iOS AVAssetImageGenerator with no time tolerance, the web a hidden <video> drawn into a canvas.

On the web, thumbnails work for files the element plays, not HLS or DASH, and media from another origin needs CORS.

What's next

Was this page helpful?
Edit on GitHub

Last updated on