问题描述
我的目标是创建一个Unity AR应用程序(稍后将其导出到Android),用户可以在其中查看IP摄像机正在播放的内容。
为此,我使用网格渲染器(在本例中为四边形)显示图像,然后在Unity世界中添加了一个指向它的AR相机。 我从Internet上获得了以下大多数代码,并被告知需要将C#脚本引用称为 LoadRawTextureData(),以便将流字节转换为纹理。
using UnityEngine.UI;
using UnityEngine.Networking;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Net;
using System.IO;
public class IPCamConfig : MonoBehavIoUr
{
[HideInInspector]
public Byte[] JpegData;
[HideInInspector]
public string resolution = "320x240";
private Texture2D camTexture;
public Stream stream;
private WebResponse resp;
public MeshRenderer frame;
private void Start()
{
GetVideo();
FindLength(stream);
}
void OnDestroy()
{
StopStream();
}
public void GetVideo()
{
// create HTTP request
resolution = "320x240";
string url = "http://192.168.1.104/videostream.asf?usr=admin&pwd=" + resolution + "&resolution=320*240";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Credentials = new NetworkCredential("username","password");
// get response
resp = req.GetResponse();
camTexture = new Texture2D(4,4,TextureFormat.ARGB32,false);
camTexture.LoadRawTextureData(JpegData);
camTexture.Apply();
GetComponent<Renderer>().material.mainTexture = camTexture;
// get response stream
stream = resp.GetResponseStream();
frame.material.color = Color.white;
StartCoroutine(GetFrame());
}
public IEnumerator GetFrame()
{
while (true)
{
int bytesToRead = FindLength(stream);
if (bytesToRead == -1)
{
// print("End of stream");
yield break;
}
int leftToRead = bytesToRead;
while (leftToRead > 0)
{
// print (leftToRead);
leftToRead -= stream.Read(JpegData,bytesToRead - leftToRead,leftToRead);
yield return null;
}
MemoryStream ms = new MemoryStream(JpegData,bytesToRead,false,true);
camTexture.LoadImage(ms.GetBuffer());
frame.material.mainTexture = camTexture;
frame.material.color = Color.white;
stream.ReadByte(); // CR after bytes
stream.ReadByte(); // LF after bytes
}
}
int FindLength(Stream stream)
{
int b;
string line = "";
int result = -1;
bool atEOL = false;
while ((b = stream.ReadByte()) != -1)
{
if (b == 10) continue; // ignore LF char
if (b == 13)
{ // CR
if (atEOL)
{ // two blank lines means end of header
stream.ReadByte(); // eat last LF
return result;
}
if (line.StartsWith("Content-Length:"))
{
result = Convert.ToInt32(line.Substring("Content-Length:".Length).Trim());
}
else
{
line = "";
}
atEOL = true;
}
else
{
atEOL = false;
line += (char)b;
}
}
return -1;
}
public void StopStream()
{
stream.Close();
resp.Close();
}
}
我已经在GetVideo()函数中实现了 LoadRawTextureData(),因为它可以在其中验证IP摄像机URL并据称从素材中渲染纹理。
相反,当我在Unity中运行应用程序时,不断出现以下错误:
UnityEngine.Texture2D:LoadRawTextureData(Byte[])
IPCamConfig:GetVideo() (at Assets/Scripts/IPCamConfig.cs:48)
IPCamConfig:Start() (at Assets/Scripts/IPCamConfig.cs:25)
还有其他我想念的东西吗?还是我必须使用另一个脚本参考/ API进行字节转换?任何帮助表示赞赏。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)