Unity 视频缩略图获取

↘锁芯ラ 提交于 2020-01-20 08:25:44
 IEnumerator GetVideoThumb(string urlpath,int index)
    {
        print(index);
       Transform go= Instantiate(VideoPlayerPrefab);
       VideoPlayer tmpVp= go.gameObject.AddComponent<VideoPlayer>();
        go.gameObject.AddComponent<IndexNumber>();
        go.GetComponent<IndexNumber>().index = index;

        tmpVp.source = VideoSource.Url;
        tmpVp.url = urlpath;
        tmpVp.sendFrameReadyEvents = true;
        //绑定的事件会不断调用
        tmpVp.frameReady += OnNewFrame;
        tmpVp.Play();
        yield return null;
        //while (tmpVp.texture == null|| tmpVp.isPlaying==false)
        //{
        //    yield return new   WaitForSeconds(1.5f);
        //}

        //Texture2D videoFrameTexture = new Texture2D(Screen.width, Screen.width,TextureFormat.ARGB32, false);
        //RenderTexture tmp = RenderTexture.GetTemporary(
        //            Screen.width, Screen.width,
        //            0,
        //            RenderTextureFormat.Default,
        //            RenderTextureReadWrite.sRGB);
        ////将texture的像素复制到RenderTexture
        //Graphics.Blit(tmpVp.texture, tmp);

        //// RenderTexture.active = tmp;
        //videoFrameTexture.ReadPixels(new Rect(0, 0, tmp.width, tmp.height), 0, 0);
        //videoFrameTexture.Apply();

        //img.sprite = Sprite.Create(videoFrameTexture, new Rect(0,0, videoFrameTexture.width, videoFrameTexture.height), new Vector2(0.5f, 0.5f));
        //// RenderTexture.active = null;
        //// 释放临时RenderTexture
        //RenderTexture.ReleaseTemporary(tmp);

        //Destroy(go.gameObject);

    }

    void OnNewFrame(VideoPlayer source, long frameIdx)
    {
         RenderTexture  renderTexture = source.texture as RenderTexture;
      
        if (frameIdx >=3)  //要用 > ,frameIdx可能会跳过这个数字
        {
          
            Texture2D videoFrameTexture = new Texture2D(Screen.width, Screen.width, TextureFormat.ARGB32, false);
            videoFrameTexture.Resize(renderTexture.width, renderTexture.height);
            RenderTexture.active = renderTexture;
            videoFrameTexture.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
            videoFrameTexture.Apply();

            AllBtnObj[source.GetComponent<IndexNumber>().index].transform.GetComponent<Image>().sprite = Sprite.Create(videoFrameTexture, new Rect(0, 0, videoFrameTexture.width, videoFrameTexture.height), new Vector2(0.5f, 0.5f));

            source.frameReady -= OnNewFrame;
            source.sendFrameReadyEvents = false;
            Destroy(source.gameObject);
        }
    }

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!