C#基于UDP实现的P2P语音聊天工具

2019-12-30 10:57:56王冬梅
  • {   byte[] buffur = new byte[fs.Length];  
  • fs.Read(buffur, 0, (int)fs.Length);    
  • return buffur;   }  
  • catch (Exception ex)   {  
  • return null;   }  
  • finally  {  
  • if (fs != null)   {  
  •   //关闭资源  
  • fs.Close();   }  
  • }   }  

    如此一来我们就把产生的语音文件发送出去了

    语音的接收与播放

    其实语音的接收和文本消息的接收没有什么不同,只不过语音发送的时候是以二进制发送的,因此我们在收到语音后 就应该写入到一个文件里面去,接收完成后,播放这段语音就行了。

    下面这段代码主要是把收到的数据保存到文件中去,这个函数式我的NetFrame里收到消息时所触发的事件,在文章前面提过的那篇文章里

     

     
    1. void tran_MessageReceived(object sender, MessageEventArgs e)   {  
    2. Msg msg = e.msg;    
    3. if (msg.Type == Consts.MESSAGE_BINARY)   {  
    4. string m = msg.Type + "->" + msg.UserName + "发来二进制消息!";   AddServerMessage(m);  
    5. if (File.Exists(recive_soundfile))   {  
    6. File.Delete(recive_soundfile);   }  
    7. FileStream fs = new FileStream(recive_soundfile, FileMode.Create, FileAccess.Write);   fs.Write(msg.ExtendMessageBytes, 0, msg.ExtendMessageBytes.Length);