我之前用的方法基本上是VideoPlayer里面的frame做同步,说实话用frame这个变量作帧同步是有些卡的,现在用VideoPlayer里面的time这个变量作同步,这个变量可赋值可获取,很方便,个人感觉比frame卡得好一点,
废话不多说,上代码,
Client
using UnityEngine;
using UnityEngine.Video;
public class ClientControl : MonoBehaviour
{
public VideoPlayer videoPlayer;
private double timer = 0;
void Start()
{
UdpManager.InitializeUdpClient();
}
void Update()
{
if (UdpManager.m_receivedMessage != null)
{
string[] msgArr = UdpManager.m_receivedMessage.Split('+');
if (msgArr.Length > 1)
{
switch (msgArr[0])
{
case "时间":
timer = double.Parse(msgArr[1]);
if (timer != 0)
{
videoPlayer.time = timer + 0.01;//加上传输信号的时间误差
timer = 0;
}
break;
}
}
UdpManager.m_receivedMessage = null;
}
}
private void OnDestroy()
{
UdpManager.Close();
}
}
Server
using UnityEngine;
using UnityEngine.Video;
public class ServerControl : MonoBehaviour
{
public VideoPlayer player;
private double timer = 0;
void Start()
{
timer = 0;
}
void Update()
{
timer += Time.deltaTime;
if (timer > 2)
{
timer = 0;
UdpManager.SendMessage("时间+" + player.time);
}
}
}
最后一个简单粗暴的UdpManager
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
using UnityEngine.Video;
public class UdpManager
{
public static string m_receivedMessage;
static IPEndPoint m_IPEndPoint;
static UdpClient m_udpClient;
public static void InitializeUdpClient()
{
m_IPEndPoint = new IPEndPoint(IPAddress.Any, 1118);
m_udpClient = new UdpClient(m_IPEndPoint);
UdpModel s = new UdpModel(m_udpClient, m_IPEndPoint);
m_udpClient.BeginReceive(EndReceive, s);
}
private static void EndReceive(IAsyncResult ar)
{
try
{
UdpModel m_UdpModel = ar.AsyncState as UdpModel;
if (m_UdpModel != null)
{
UdpClient udpClient = m_UdpModel.m_udpclient;
IPEndPoint ip = m_UdpModel.m_ip;
Byte[] receiveBytes = udpClient.EndReceive(ar, ref ip);
string msg = Encoding.UTF8.GetString(receiveBytes);
m_receivedMessage = msg;
udpClient.BeginReceive(EndReceive, m_UdpModel);
}
}
catch (Exception ex)
{
//处理异常
}
}
private class UdpModel
{
public UdpClient m_udpclient = null;
public IPEndPoint m_ip;
public UdpModel(UdpClient udpclient, IPEndPoint ip)
{
this.m_udpclient = udpclient;
this.m_ip = ip;
}
}
public static void Close()
{
if (m_udpClient != null)
{
m_udpClient.Close();
m_udpClient = null;
}
}
/// <summary>
/// 发送数据
/// </summary>
/// <param name="obj"></param>
public static void SendMessage(string message)
{
UdpClient myUdpClient = new UdpClient();
IPEndPoint endpoint;
myUdpClient = new UdpClient(new IPEndPoint(IPAddress.Any, 8800));
endpoint = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 1118);
byte[] bytes = Encoding.UTF8.GetBytes(message);
try
{
myUdpClient.Send(bytes, bytes.Length, endpoint);
myUdpClient.Close();
}
catch (Exception err)
{
Console.Write(err.Message, "发送失败");
}
finally
{
myUdpClient.Close();
}
}
}
|