我正在从 kinect 设备获取音频并将这些字节数组发送到客户端,客户端接收这些字节并使用 xna DynamicSoundEffectInstance 类播放,但我面临的问题是客户端接收到一些字节并且程序自动终止而没有任何异常服务器代码
KinectSensor kinectsenser;
Thread obj;
TcpClient client;
TcpListener server;
NetworkStream ns;
Stream kinectaudio;
soundcontainer.SoundData sound =null;
Thread obj1 = null;
Object objt = new Object();
public MainWindow()
{
InitializeComponent();
server = new TcpListener(IPAddress.Parse("127.0.0.1"), 45000);
server.Start();
client = server.AcceptTcpClient();
ns = client.GetStream();
sound = new SoundData();
obj1 = new Thread(send);
}
void audio()
{
byte[] soundSampleBuffer = new byte[1000];
kinectaudio = kinectsenser.AudioSource.Start();
obj1.Start();
while (true)
{
lock (objt)
{
int count = kinectaudio.Read(soundSampleBuffer, 0, soundSampleBuffer.Length);
sound.data = soundSampleBuffer;
}
}
}
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
if (KinectSensor.KinectSensors.Count == 0)
{
MessageBox.Show("no Kinect Device is attched");
Application.Current.Shutdown();
}
kinectsenser = KinectSensor.KinectSensors[0];
kinectsenser.Start();
audio();
}
void send()
{
while (true)
{
lock (objt)
{
soundcontainer.SoundData i = new SoundData();
i.data = sound.data;
if (i.data != null)
{
if (ns.CanWrite)
{
ns.Write(i.data, 0, i.data.Length);
ns.Flush();
}
}
}
}
}
客户端代码如下:
public partial class MainWindow : Window
{
TcpClient client;
NetworkStream ns;
Thread iiui;
public MainWindow()
{
InitializeComponent();
client = new TcpClient();
IPAddress ip=IPAddress.Parse("127.0.0.1");
client.Connect(ip, 45000);
ns = client.GetStream();
iiui = new Thread(start);
iiui.Start();
}
void start()
{
DynamicSoundEffectInstance sound = new DynamicSoundEffectInstance(16000, AudioChannels.Mono);
Microsoft.Xna.Framework.FrameworkDispatcher.Update();
sound.Play();
IFormatter formater = new BinaryFormatter();
while (true)
{
byte[] temp = new byte[65536];
ns.Read(temp, 0, temp.Length);
sound.SubmitBuffer(temp, 0, temp.Length);
}
}
}