[Unity] Unity中基于RPC机制实现摄像头视频传输

查看:1446 |回复:6 | 2015-6-24 10:56:30

您需要 登录 才可以下载或查看,没有账号?注册

x
本帖最后由 大西几 于 2021-2-24 16:15 编辑

Unity中的RPC机制不能直接将视频进行传输,
所以要进行视频帧图片到字节的转换,在将字节流进行传输。

首先,客户端的代码如下


  1. using UnityEngine;
  2. using System.Collections;

  3. public class Client : MonoBehaviour {
  4.         //要连接的服务器地址
  5.         //string IP = "127.0.0.1";//本地电脑地址
  6.     string IP = "192.168.1.100";
  7.     public  Texture2D m_recevieTex;
  8.    // string IP = "192.168.1.102";
  9.         //要连接的端口
  10.         int Port = 10100;
  11.         //聊天信息
  12.         string Message = "";
  13.         //声明一个二维向量
  14.         Vector2 Sc;
  15.     public UITexture m_uiCameraPlane;        
  16.         void OnGUI(){
  17.                 //端类型的状态
  18.                 switch(Network.peerType){
  19.                         //禁止客户端连接运行, 服务器未初始化
  20.                         case NetworkPeerType.Disconnected:
  21.                                 StartConnect();
  22.                             break;
  23.                         //运行于服务器端
  24.                         case NetworkPeerType.Server:
  25.                             break;
  26.                         //运行于客户端
  27.                         case NetworkPeerType.Client:
  28.                             OnClient();
  29.                             break;
  30.                         //正在尝试连接到服务器
  31.                         case NetworkPeerType.Connecting:
  32.                                 break;
  33.                 }
  34.         }
  35.                
  36.         void StartConnect(){
  37.                 if (GUILayout.Button("连接服务器")){
  38.                         NetworkConnectionError error = Network.Connect(IP,Port);
  39.                         //连接状态
  40.                         switch(error){
  41.                                 case NetworkConnectionError.NoError:
  42.                                     break;
  43.                             default:
  44.                                 Debug.Log("客户端错误"+error);
  45.                                     break;
  46.                         }
  47.                 }
  48.         }
  49.         
  50.         void OnClient(){
  51.                 //创建开始滚动视图
  52.                 Sc = GUILayout.BeginScrollView(Sc,GUILayout.Width(280),GUILayout.Height(400));
  53.                 //绘制纹理, 显示内容
  54.                 GUILayout.Box(Message);
  55.                 //文本框
  56.                 Message = GUILayout.TextArea(Message);
  57.                 if (GUILayout.Button("发送")){
  58.                         //发送给接收的函数, 模式为全部, 参数为信息
  59.                         //networkView.RPC("ReciveMessage", RPCMode.All, Message);
  60.             networkView.RPC("ReciveCameraTex", RPCMode.All, m_recevieTex.EncodeToJPG());
  61.                 }
  62.                 //结束滚动视图, 注意, 与开始滚动视图成对出现
  63.                 GUILayout.EndScrollView();
  64.                
  65.         }
  66.         
  67.     //接收请求的方法. 注意要在上面添加[RPC]
  68.         [RPC]
  69.         void ReciveMessage(string msg, NetworkMessageInfo info){
  70.                 //刚从网络接收的数据的相关信息,会被保存到NetworkMessageInfo这个结构中
  71.                 Message = "发送端"+info.sender  +"消息"+msg;
  72.         }
  73.     [RPC]
  74.     void ReciveCameraTex(byte[] camTex, NetworkMessageInfo info)
  75.     {
  76.         m_recevieTex=new Texture2D(Screen.width, Screen.height);
  77.         m_recevieTex.LoadImage(camTex);
  78.         m_uiCameraPlane.mainTexture = m_recevieTex;
  79.     }
  80.         // Use this for initialization
  81.         void Start () {
  82.         
  83.         }
  84.         
  85.         // Update is called once per frame
  86.         void Update () {
  87.         
  88.         }
  89. }
点击此处复制文本

客户端主要是用来接收的,所以比较简单。在接收函数ReciveCameraTex中直接进行转换就可以了。
相对的服务端就比较复杂一点,代码如下



  1. using UnityEngine;
  2. using System.Collections;
  3. public class Severs : MonoBehaviour {
  4.     public UITexture m_cameraShowTex;
  5.     public Texture2D m_sendTex;
  6.     //public Texture2D m_sendTexText;
  7.     public byte[] m_tempBytes;
  8.     private RenderTexture m_currentRT;
  9.     private RenderTexture m_renderTex;
  10.         int Port = 10100;
  11.         string Message = "";
  12.     string m_cameraName;
  13.         //声明一个二维向量
  14.         Vector2 Sc;
  15.     WebCamTexture m_cameraTex;
  16.     float m_zoomRate;//焦距
  17.     bool m_isPlay=false;
  18.     bool m_isSend = false;
  19.     // Use this for initialization
  20.     void Start()
  21.     {
  22.         m_zoomRate = 1;
  23.         m_renderTex = new RenderTexture(300, 300, 24, RenderTextureFormat.ARGB32);
  24.        // m_renderTex = new RenderTexture(Screen.width,Screen.height, 24, RenderTextureFormat.ARGB32);
  25.         m_sendTex = new Texture2D(m_renderTex.width,m_renderTex.height);
  26.         Camera.main.targetTexture = m_renderTex;
  27.         StartCoroutine(openCamera(0));
  28.     }

  29.     // Update is called once per frame
  30.     void Update()
  31.     {
  32.     }
  33.     IEnumerator openCamera(int whichOne)
  34.     {
  35.         yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
  36.         if (Application.HasUserAuthorization(UserAuthorization.WebCam))
  37.         {
  38.             //可以通过下面的这个数组的索引来选择调用手机上的前置或者后置摄像头,另外这个可以自动对焦
  39.             WebCamDevice[] devices = WebCamTexture.devices;
  40.             if (devices.Length <= whichOne)
  41.             {
  42.                 m_cameraName = devices[0].name;
  43.             }
  44.             else
  45.             {
  46.                 m_cameraName = devices[whichOne].name;
  47.                 if (whichOne > 0)
  48.                 {
  49.                    /* Quaternion temp = m_uiCameraPlane.transform.localRotation;
  50.                     temp.eulerAngles = new Vector3(0, 0, 90);
  51.                     m_uiCameraPlane.transform.localRotation = temp;*/
  52.                 }
  53.             }
  54.             m_cameraTex = new WebCamTexture(m_cameraName, Screen.width, Screen.height, 30);
  55.             m_cameraTex.anisoLevel = 9;
  56.             float heightRate = Screen.height / m_cameraTex.height;
  57.             float widthRate = Screen.width / m_cameraTex.width;
  58.             //Debug.Log(heightRate.ToString());
  59.             //Debug.Log(widthRate.ToString());
  60.             m_zoomRate = heightRate > widthRate ? heightRate : widthRate;
  61.             if (m_zoomRate > 2)
  62.             {
  63.                 m_zoomRate = 2;
  64.             }
  65.             m_cameraTex.Play();
  66.             m_isPlay = true;
  67.         }
  68.     }  
  69.         //OnGUI方法,所有GUI的绘制都需要在这个方法中实现
  70.         void OnGUI(){

  71.                 //Network.peerType是端类型的状态:
  72.                 //即disconnected, connecting, server 或 client四种
  73.                 switch(Network.peerType){
  74.                         //禁止客户端连接运行, 服务器未初始化
  75.                         case NetworkPeerType.Disconnected:
  76.                                 StartServer();
  77.                             break;
  78.                         //运行于服务器端
  79.                         case NetworkPeerType.Server:
  80.                                 OnServer();
  81.                             break;
  82.                         //运行于客户端
  83.                         case NetworkPeerType.Client:
  84.                             break;
  85.                         //正在尝试连接到服务器
  86.                         case NetworkPeerType.Connecting:
  87.                                 break;
  88.                 }

  89.         if (m_isPlay)
  90.         {

  91.             m_cameraShowTex.mainTexture = m_cameraTex;
  92.             //NGUIDebug.Log(" cameraTexture.height:" + cameraTexture.height.ToString() + "cameraTexture.width:" + cameraTexture.width.ToString());
  93.             m_cameraShowTex.width= m_cameraTex.width;
  94.             m_cameraShowTex.height = m_cameraTex.height;

  95.            // m_sendTex = RTImage(Camera.main);
  96.            // m_tempBytes = m_sendTex.EncodeToPNG();
  97.             if (m_isSend)
  98.             {
  99.                 StartCoroutine(changeSendTexToBytes());
  100.             }
  101.         }
  102.         }
  103.     IEnumerator changeSendTexToBytes()
  104.     {
  105.         m_isPlay = false;
  106.         RTImage();
  107.         m_tempBytes = m_sendTex.EncodeToPNG();
  108.         yield return new WaitForSeconds(0.35f);
  109.         networkView.RPC("ReciveCameraTex", RPCMode.All, m_tempBytes);
  110.         m_isPlay = true;
  111.     }
  112.     void RTImage()
  113.     {
  114.         m_currentRT = RenderTexture.active;
  115.         RenderTexture.active = m_renderTex;
  116.         Camera.main.Render();
  117.         m_sendTex.ReadPixels(new Rect(0, 0, m_cameraShowTex.width, m_cameraShowTex.height), 0, 0);
  118.         m_sendTex.Apply();
  119.         RenderTexture.active = m_currentRT;
  120.         
  121.     }
  122.     Texture2D RTImage(Camera cam)
  123.     {
  124.         RenderTexture currentRT = RenderTexture.active;
  125.         RenderTexture.active = cam.targetTexture;
  126.         cam.Render();
  127.         Texture2D image = new Texture2D(cam.targetTexture.width, cam.targetTexture.height);
  128.         image.ReadPixels(new Rect(0, 0, cam.targetTexture.width, cam.targetTexture.height), 0, 0);
  129.         image.Apply();
  130.         RenderTexture.active = currentRT;
  131.         return image;
  132.     }
  133.         void StartServer(){
  134.                 //当用户点击按钮的时候为true
  135.                 if ( GUI.Button(new Rect(10, 10, 100, 20),"创建服务器")) {
  136.                         //初始化本机服务器端口,第一个参数就是本机接收多少连接
  137.                         NetworkConnectionError error = Network.InitializeServer(12,Port,false);
  138.                         //连接状态
  139.                         switch(error){
  140.                                 case NetworkConnectionError.NoError:
  141.                                     break;
  142.                             default:
  143.                                 Debug.Log("服务端错误"+error);
  144.                                     break;
  145.                         }
  146.                 }
  147.         }
  148.         
  149.         void OnServer(){
  150.                  GUI.Label(new Rect(10, 30, 100, 20),"服务端已经运行,等待客户端连接");
  151.                 //Network.connections是所有连接的玩家, 数组[]
  152.                 //取客户端连接数.
  153.                 int length = Network.connections.Length;
  154.                 //按数组下标输出每个客户端的IP,Port
  155.                 for (int i=0; i<length; i++)
  156.                 {
  157.             GUI.Label(new Rect(10, 50, 300, 20),"客户端" + i);
  158.                         GUI.Label(new Rect(10, 70, 300, 20),"客户端ip"+Network.connections[i].ipAddress);
  159.                         GUI.Label(new Rect(10, 90, 300, 20),"客户端端口"+Network.connections[i].port);
  160.                          GUI.Label(new Rect(10, 100, 300, 20),"-------------------------------");
  161.                 }
  162.                 //当用户点击按钮的时候为true
  163.                 if (GUI.Button(new Rect(10, 120,300, 20),"断开服务器")){
  164.                         Network.Disconnect();
  165.                 }
  166.         if(GUI.Button(new Rect(500, 120,300, 20),"发送"))
  167.         {
  168.             m_isSend = true;
  169.    
  170.         }
  171.         }
  172.         //接收请求的方法. 注意要在上面添加[RPC]
  173.         [RPC]
  174.     void ReciveCameraTex(byte[] camTex, NetworkMessageInfo info)
  175.     {
  176.         //m_sendTexText.LoadImage(m_tempBytes);
  177.     }
  178.         
  179. }
点击此处复制文本


因为Unity中获取得到的摄像头视频,不能直接转换成字节必须要转换成Textture2D之后在使用EncodeToPNG()函数转换成字节,而将摄像头的WebCamTexture也不能直接转换成Texture2D,在官网上提供了这样一个转换方法


  1.   Texture2D RTImage(Camera cam)
  2.     {
  3.         RenderTexture currentRT = RenderTexture.active;
  4.         RenderTexture.active = cam.targetTexture;
  5.         cam.Render();
  6.         Texture2D image = new Texture2D(cam.targetTexture.width, cam.targetTexture.height);
  7.         image.ReadPixels(new Rect(0, 0, cam.targetTexture.width, cam.targetTexture.height), 0, 0);
  8.         image.Apply();
  9.         RenderTexture.active = currentRT;
  10.         return image;
  11.     }
点击此处复制文本


好了大功告成,我写的比较粗糙,没有做缓存处理和关键帧的计算,主要集中在怎么转换摄像头的WebCamTexture到字节上,要有一定写UnityRPC基础的童鞋才可以看得懂并进行调试我的代码,在两个电脑上比较流畅,在手机上还是比较卡。
原帖地址:http://blog.csdn.net/zhangxiao13627093203/article/details/46545751
image.png
2015-6-24 10:56:30  
 赞 赞 1

使用道具 登录

6个回答,把该问题分享到群,邀请大神一起回答。
3#
元素帖子强,满满正能量!
回复 收起回复
2015-6-24 11:55:09   回复
 赞 赞 1

使用道具 登录

4#
看完楼主的帖子,感觉自己萌萌哒~!
回复 收起回复
2015-6-24 18:30:17   回复
 赞 赞 1

使用道具 登录

5#
上午好
回复 收起回复
2018-11-9 11:28:59   回复
 赞 赞 1

使用道具 登录

6#
感谢!感谢
回复 收起回复
2018-11-9 16:28:31   回复
 赞 赞 1

使用道具 登录

7#
资源甚好,发帖艰辛,且阅且珍惜!
回复 收起回复
2018-11-9 17:09:04   回复
 赞 赞 1

使用道具 登录

CG 游戏行业专业问题

Unity3D技术手机游戏引擎手游引擎
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表