Search code examples
androidexoplayerexoplayer2.x

In ExoPlayer how do I show the thumbnail of the first frame after loading a media source and seeking to a position instead of it being blank?


How do I show the first frame of the video after the Fragment is resumed instead of the video player being blank?


Solution

  • 1.) Add surface_type="texture_view" to PlayerView

     <com.google.android.exoplayer2.ui.PlayerView
        android:id="@+id/player_view"
        app:surface_type="texture_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    

    2.) Add thumbnail view in front of PlayerView in layout

    <View
        android:id="@+id/view_thumbnail_background"
        android:visibility="invisible"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/black" />
    
    <ImageView
        android:id="@+id/image_thumbnail"
        android:visibility="invisible"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    

    3.) Create a method to get the Bitmap from the TextureView

    private fun setVideoThumbnail() {
        val textureView = playerView.videoSurfaceView as TextureView
        val bitmap = textureView.bitmap
        thumbnailImage.setImageBitmap(bitmap)
        thumbnailBackground.visibility = View.VISIBLE
        thumbnailImage.visibility = View.VISIBLE
    }
    

    4.) In onPause call

    setVideoThumbnail()
    // destroy player or not depending
    

    5.) Add an onClick listener to thumbnailImage in onViewCreated

    thumbnailImage.setOnClickListener {
        // make sure player is re-created and media source is loaded, prepared, and seekTo
        player.playWhenReady = true
    
        thumbnailBackground.visibility = View.INVISIBLE
        thumbnailImage.visibility = View.INVISIBLE
    }