Created
May 17, 2019 06:03
-
-
Save realpacific/f4f4df0932339e17359ad93af2cd5649 to your computer and use it in GitHub Desktop.
BindingAdapter code for binding xml values to PlayerView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@BindingAdapter("video_url", "on_state_change") | |
fun PlayerView.loadVideo(url: String, callback: PlayerStateChange) { | |
if (url == null) return | |
val player = ExoPlayerFactory.newSimpleInstance( | |
context, DefaultRenderersFactory(context), DefaultTrackSelector(), | |
DefaultLoadControl() | |
) | |
player.playWhenReady = true | |
player.repeatMode = Player.REPEAT_MODE_ALL | |
// When changing track, retain the latest frame instead of showing a black screen | |
setKeepContentOnPlayerReset(true) | |
// We'll show the controller | |
this.useController = true | |
// Provide url to load the video from here | |
val mediaSource = ExtractorMediaSource.Factory( | |
DefaultHttpDataSourceFactory("Demo") | |
).createMediaSource(Uri.parse(url)) | |
player.prepare(mediaSource) | |
this.player = player | |
this.player!!.addListener(object : Player.EventListener { | |
override fun onPlayerError(error: ExoPlaybackException?) { | |
super.onPlayerError(error) | |
this@loadVideo.context.toast("Oops! Error occurred while playing media.") | |
} | |
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) { | |
super.onPlayerStateChanged(playWhenReady, playbackState) | |
if (playbackState == Player.STATE_BUFFERING) callback.onVideoBuffering(player) // Buffering.. set progress bar visible here | |
if (playbackState == Player.STATE_READY){ | |
// [PlayerView] has fetched the video duration so this is the block to hide the buffering progress bar | |
callback.onVideoDurationRetrieved(this@loadVideo.player.duration, player) | |
} | |
if (playbackState == Player.STATE_READY && player.playWhenReady){ | |
// [PlayerView] has started playing/resumed the video | |
callback.onStartedPlaying(player) | |
} | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment