Search Unity

Video How to get texture from a recorded video so that it can be shown on a custom gallery?

Discussion in 'Audio & Video' started by zyonneo, Jan 12, 2021.

  1. zyonneo

    zyonneo

    Joined:
    Apr 13, 2018
    Posts:
    386
    I am recording a video using a screen recording plugin replay kit. So after recording the video I want to create an image for the video gallery by taking a screenshot of the video while playing. I tried the following code but failed. I have added a video player on the heirarchy and dragged a dropped a Render texture created on the project window.

    Code (CSharp):
    1.  
    2. [SerializeField] private VideoPlayer videoPlayer;
    3.  protected override void OnEnable()
    4.     {
    5.         videoPlayer.prepareCompleted += PrepareComplete;
    6.     }
    7.  
    8. private void CopyVideoScreenshot(string sourceVideoPath)
    9.     {
    10.         Debug.Log("Source path == "+sourceVideoPath);
    11.        // string path = "file://" + sourceVideoPath;
    12.         videoPlayer.source = VideoSource.Url;
    13.         videoPlayer.url = sourceVideoPath;
    14.         videoPlayer.Prepare();    
    15.         //videoPlayer.Play();
    16.         Debug.Log("Video Playing");
    17.     }
    18.  
    19.  private void PrepareComplete(VideoPlayer videoplayer)
    20.     {
    21.         Debug.Log("Prepare Video");
    22.         RenderTexture renderTexture = videoPlayer.targetTexture;
    23.         int width = videoPlayer.texture.width;
    24.         int height = videoPlayer.texture.height;
    25.         Texture2D texture= new Texture2D(width, height, TextureFormat.RGBA32, false);
    26.         if (texture.width != renderTexture.width || texture.height != renderTexture.height)
    27.         {
    28.             texture.Resize(renderTexture.width, renderTexture.height);
    29.         }
    30.         //RenderTexture.active = renderTexture;
    31.         texture.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
    32.         texture.Apply();
    33.         Debug.Log("Texture Name ="+texture.name);
    34.         //RenderTexture.active = null;
    35.  
    36.       //Save on persistent data path
    37.    }
    38.  protected override void OnDisable()
    39.     {
    40.         videoPlayer.prepareCompleted -= PrepareComplete;  
    41.     }
    42.    
    For some reason, the PrepareComplete() method is not getting called in Android(version 10 and Unity 2019.4.17f1).
    How is prepareCompleted event called?While videoPlayer.Play() or videoPlayer.Prepare()