Skip to content

IlyaPavlovskii/YouTubePlayer

Repository files navigation

YouTubePlayer

Maven Central Kotlin Compose Multiplatform

badge-android badge-ios

YouTube kotlin multiplatform player. The YouTubePlayer composable allows you to embed a YouTube video player in your Jetpack Compose app.

Donate

If you want to thank me or contribute to the development of the backlog, you may donate me. That helps me to concentrate more on the project.

"PayPal" "Buy Me A Coffee"

You also might subscribe me on the next platforms to see any updates of my topics

medium habr

Install

You can add this library to your project using Gradle.

Multiplatform To add to a multiplatform project, add the dependency to the common source-set:

repositories {
    mavenCentral()
}

kotlin {
    sourceSets {
        commonMain {
            dependencies {
                implementation("io.github.ilyapavlovskii:youtubeplayer-compose:${latest_version}")
            }
        }
    }
}

Usage

val coroutineScope = rememberCoroutineScope()
val hostState = remember { YouTubePlayerHostState() }

when(val state = hostState.currentState) {
    is YouTubePlayerState.Error -> {
        Text(text = "Error: ${state.message}")
    }
    YouTubePlayerState.Idle -> {
        // Do nothing, waiting for initialization
    }
    is YouTubePlayerState.Playing -> {
        // Update UI button states
    }
    YouTubePlayerState.Ready -> coroutineScope.launch {
        hostState.loadVideo(YouTubeVideoId("ufKj1sBrC4Q"))
    }
}

YouTubePlayer(
    modifier = Modifier
        .fillMaxWidth()
        .height(300.dp)
        .gesturesDisabled(),
    hostState = hostState,
    options = SimpleYouTubePlayerOptionsBuilder.builder {
        autoplay(true)
        controls(false)
        rel(false)
        ivLoadPolicy(false)
        ccLoadPolicy(false)
        fullscreen = true
    },
)

Composable function has the next major params:

  • options - to player options builder. All parameters wrapped from official youtube iframe documentation.
  • hostState - controller for track youtube player state and execute one time commands

YouTubePlayerHostState

The main controller. Contains 2 major public components:

  • currentState - defines actual youtube player state on the screen. Might be: Idle, Ready, Playing, Error
  • executeCommand - suspend function to execution player commands. Receives only one argument - YouTubeExecCommand. Also have an additional sugar functions like:
suspend fun loadVideo(videoId: YouTubeVideoId) = executeCommand(YouTubeExecCommand.LoadVideo(videoId))
suspend fun play() = executeCommand(YouTubeExecCommand.Play)
suspend fun pause() = executeCommand(YouTubeExecCommand.Pause)
suspend fun seekTo(duration: Duration) = executeCommand(YouTubeExecCommand.SeekTo(duration))
suspend fun seekBy(duration: Duration) = executeCommand(YouTubeExecCommand.SeekBy(duration))
suspend fun mute() = executeCommand(YouTubeExecCommand.Mute)
suspend fun unMute() = executeCommand(YouTubeExecCommand.Unmute)
suspend fun setVolume(volume: Int) = executeCommand(YouTubeExecCommand.SetVolume(volume))
suspend fun setPlaybackRate(rate: Float) = executeCommand(YouTubeExecCommand.SetPlaybackRate(rate))
suspend fun toggleFullScreen() = executeCommand(YouTubeExecCommand.ToggleFullscreen)

YouTube player state defines actual youtube player state on the screen. Contains the next possible states:

  • Idle - Idle state means that player is not initialized yet
  • Ready - Means that player is ready to play
  • Playing - player is playing video. Contains the next params:
videoId: YouTubeVideoId - id of the video that is playing
duration: Duration - duration of the video
currentTime: Duration - current time of the video
quality: YouTubeEvent.PlaybackQualityChange.Quality - quality of the video, see [YouTubeEvent.PlaybackQualityChange.Quality]
isPlaying: Boolean - is video playing
  • Error - Defines error state with error message inside.
  • LoadVideo(val videoId: YouTubeVideoId,val startSeconds: Duration) - load video by youtube id. Possible to start with default start time offset.

  • Play - play video

  • Pause - pause video

  • SeekTo(val duration: Duration) - seek video to a specified time

  • SeekBy(val duration: Duration) - seek video by a specified time

  • Mute - mute sound

  • Unmute - unmute sound

  • SetVolume(val volumePercent: Int) - set volume. Expected argument value from 0 to 100.

  • NextVideo - navigate to a next video

  • PreviousVideo - navigate to a previous video

  • SetLoop(val loop: Boolean) - repeat video. Managed by argument.

  • SetShuffle(val shuffle: Boolean) - shuffle videos. Managed by argument.

  • Ready - calls when youtube player initialization complete
  • PlaybackQualityChange(val quality: Quality) - calls when player quality changes
  • Error(val error: String) - error handle event. See argument for details.
  • VideoDuration(val duration: Duration) - calls when video duration initialized
  • StateChanged(val state: State) - calls when video state changed: UNSTARTED,ENDED, PLAYING, PAUSED, BUFFERING, CUED.
  • TimeChanged(val time: Duration) - timestamp changed
  • OnVideoIdHandled(val videoId: YouTubeVideoId) - callback when video loaded

Sample

Sample

LICENSE

Copyright 2024 Ilia Pavlovskii

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.