Search code examples
androidkotlinandroid-jetpack-composeandroid-animation

Android Jetpack Compose how to show a MP4 video as an animation


I was given a task to show an animation for a couple of screens. I was given the animation as a mp4 file. From my understanding jetpack compose animations don't use MP4 file but rather drawable. I was wondering what is the correct approach to show an animation as a video or just show a video. Thank You for your time.


Solution

  • You can play MP4 videos using ExoPlayer. You can refer to the below example crafted by me.

    Example

    How to use exoplayer in Jetpack Compose. I have used exoplayer in one of my recent projects. so this may be helpful for you as well.

    gradle dependency

    implementation 'com.google.android.exoplayer:exoplayer:2.18.7'
    

    Composable Functions

    @Composable
    fun ExoplayerExample() {
    
        val context = LocalContext.current
    
        val mediaItem = MediaItem.Builder()
            .setUri("your-uri")
            .build()
        val exoPlayer = remember(context, mediaItem) {
            ExoPlayer.Builder(context)
                .build()
                .also { exoPlayer ->
                    exoPlayer.setMediaItem(mediaItem)
                    exoPlayer.prepare()
                    exoPlayer.playWhenReady = false
                    exoPlayer.repeatMode = REPEAT_MODE_OFF
                }
        }
    
        DisposableEffect(
            AndroidView(factory = {
                StyledPlayerView(context).apply {
                    player = exoPlayer
                }
            })
        ) {
            onDispose { exoPlayer.release() }
        }
    
        
    }
    

    this way you can use exoplayer in Jetpack Compose. You can customize it as per your requirement.