C#基于UDP实现的P2P语音聊天工具(1)
这篇文章主要是一个应用,使用udp传送语音和文本等信息。在这个系统中没有服务端和客户端,相互通讯都是直接相互联系的。能够很好的实现效果。
语音获取
要想发送语音信息,首先得获取语音,这里有几种方法,一种是使用DirectX的DirectXsound来录音,我为了简便使用一个开源的插件NAudio来实现语音录取。 在项目中引用NAudio.dll
- //------------------录音相关-----------------------------
- private IWaveIn waveIn;
- private WaveFileWriter writer;
- private void LoadWasapiDevicesCombo()
- {
- var deviceEnum = new MMDeviceEnumerator();
- var devices = deviceEnum.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.Active).ToList();
- comboBox1.DataSource = devices;
- comboBox1.DisplayMember = "FriendlyName";
- }
- private void CreateWaveInDevice()
- {
- waveIn = new WaveIn();
- waveIn.WaveFormat = new WaveFormat(8000, 1);
- waveIn.DataAvailable += OnDataAvailable;
- waveIn.RecordingStopped += OnRecordingStopped;
- }
- void OnDataAvailable(object sender, WaveInEventArgs e)
- {
- if (this.InvokeRequired)
- {
- this.BeginInvoke(new EventHandler<WaveInEventArgs>(OnDataAvailable), sender, e);
- }
- else
- {
- writer.Write(e.Buffer, 0, e.BytesRecorded);
- int secondsRecorded = (int)(writer.Length / writer.WaveFormat.AverageBytesPerSecond);
- if (secondsRecorded >= 10)//最大10s
- {
- StopRecord();
- }
- else
- {
- l_sound.Text = secondsRecorded + " s";
- }
- }
- }
- void OnRecordingStopped(object sender, StoppedEventArgs e)
- {
- if (InvokeRequired)
- {
- BeginInvoke(new EventHandler<StoppedEventArgs>(OnRecordingStopped), sender, e);
- }
- else
- {
- FinalizeWaveFile();
- }
- }
- void StopRecord()
- {
- AllChangeBtn(btn_luyin, true);
- AllChangeBtn(btn_stop, false);
- AllChangeBtn(btn_sendsound, true);
- AllChangeBtn(btn_play, true);
- //btn_luyin.Enabled = true;
- //btn_stop.Enabled = false;
- //btn_sendsound.Enabled = true;
- //btn_play.Enabled = true;
- if (waveIn != null)
- waveIn.StopRecording();
- //Cleanup();
- }
- private void Cleanup()
- {
- if (waveIn != null)
- {
- waveIn.Dispose();
- waveIn = null;
- }
- FinalizeWaveFile();
- }
- private void FinalizeWaveFile()
- {
- if (writer != null)
- {
- writer.Dispose();
- writer = null;
- }
- }
- //开始录音
- private void btn_luyin_Click(object sender, EventArgs e)
- {
- btn_stop.Enabled = true;
- btn_luyin.Enabled = false;
- if (waveIn == null)
- {
- CreateWaveInDevice();
- }
- if (File.Exists(soundfile))
- {
- File.Delete(soundfile);
- }
- writer = new WaveFileWriter(soundfile, waveIn.WaveFormat);
- waveIn.StartRecording();
- }
上面的代码实现了录音,并且写入文件p2psound_A.wav

语音发送
获取到语音后我们要把语音发送出去
当我们录好音后点击发送,这部分相关代码是
- MsgTranslator tran = null;
- ublic Form1()
- {
- InitializeComponent();
- LoadWasapiDevicesCombo();//显示音频设备
- Config cfg = SeiClient.GetDefaultConfig();
- cfg.Port = 7777;
- UDPThread udp = new UDPThread(cfg);
- tran = new MsgTranslator(udp, cfg);
- tran.MessageReceived += tran_MessageReceived;
- tran.Debuged += new EventHandler<DebugEventArgs>(tran_Debuged);
- }
- private void btn_sendsound_Click(object sender, EventArgs e)
- {
- if (t_ip.Text == "")
- {
- MessageBox.Show("请输入ip");
- return;
- }
- if (t_port.Text == "")
- {
- MessageBox.Show("请输入端口号");
- return;
- }
- string ip = t_ip.Text;
- int port = int.Parse(t_port.Text);
- string nick = t_nick.Text;
- string msg = "语音消息";
- IPEndPoint remote = new IPEndPoint(IPAddress.Parse(ip), port);
- Msg m = new Msg(remote, "zz", nick, Commands.SendMsg, msg, "Come From A");
- m.IsRequireReceive = true;
- m.ExtendMessageBytes = FileContent(soundfile);
- m.PackageNo = Msg.GetRandomNumber();
- m.Type = Consts.MESSAGE_BINARY;
- tran.Send(m);
- }
- private byte[] FileContent(string fileName)
- {
- FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
- try
- {
- 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里收到消息时所触发的事件,在文章前面提过的那篇文章里
- void tran_MessageReceived(object sender, MessageEventArgs e)
- {
- Msg msg = e.msg;
- if (msg.Type == Consts.MESSAGE_BINARY)
- {
- string m = msg.Type + "->" + msg.UserName + "发来二进制消息!";
- AddServerMessage(m);
- if (File.Exists(recive_soundfile))
- {
- File.Delete(recive_soundfile);
- }
- FileStream fs = new FileStream(recive_soundfile, FileMode.Create, FileAccess.Write);
- fs.Write(msg.ExtendMessageBytes, 0, msg.ExtendMessageBytes.Length);
- fs.Close();
- //play_sound(recive_soundfile);
- ChangeBtn(true);
- }
- else
- {
- string m = msg.Type + "->" + msg.UserName + "说:" + msg.NormalMsg;
- AddServerMessage(m);
- }
- }
收到语音消息后,我们要进行播放,播放时仍然用刚才那个插件播放
- //--------播放部分----------
- private IWavePlayer wavePlayer;
- private WaveStream reader;
- public void play_sound(string filename)
- {
- if (wavePlayer != null)
- {
- wavePlayer.Dispose();
- wavePlayer = null;
- }
- if (reader != null)
- {
- reader.Dispose();
- }
- reader = new MediaFoundationReader(filename, new MediaFoundationReader.MediaFoundationReaderSettings() { SingleReaderObject = true });
- if (wavePlayer == null)
- {
- wavePlayer = new WaveOut();
- wavePlayer.PlaybackStopped += WavePlayerOnPlaybackStopped;
- wavePlayer.Init(reader);
- }
- wavePlayer.Play();
- }
- private void WavePlayerOnPlaybackStopped(object sender, StoppedEventArgs stoppedEventArgs)
- {
- if (stoppedEventArgs.Exception != null)
- {
- MessageBox.Show(stoppedEventArgs.Exception.Message);
- }
- if (wavePlayer != null)
- {
- wavePlayer.Stop();
- }
- btn_luyin.Enabled = true;
- }private void btn_play_Click(object sender, EventArgs e)
- {
- btn_luyin.Enabled = false;
- play_sound(soundfile);
- }


在上面演示了接收和发送一段语音消息的界面
技术总结
主要用到的技术就是UDP和NAudio的录音和播放功能
其中用到的UDP传输类我放在了github上面 地址在我的博客左边的个人介绍里有地址 项目地址 https://github.com/zhujunxxxxx/ZZNetFrame
希望这篇文章能够提供一个思路。
C#基于UDP实现的P2P语音聊天工具(1)的更多相关文章
- c#基于udp实现的p2p语音聊天工具
原创性申明 此博文的出处 为 http://blog.csdn.net/zhujunxxxxx/article/details/40124773假设进行转载请注明出处.本文作者原创,邮箱zhujunx ...
- Android 即时语音聊天工具 开发
使用融云SDK 1. 功能需求分析 1.1 核心功能需求: * 即时通讯 * 文字聊天 * 语音聊天 1.2 辅助功能需求: * 注册.登录 * 好友添加功能 * 好友关系管理 2. 融云即时通讯平台 ...
- 基于Nodejs开发的web即时聊天工具
由于公司需要开发web即时聊天的功能,开始时我们主要的实施方法是用jquery的ajax定时(10秒)轮询向服务器请求,由于是轮询请求,对 服务器的压力比较大.我们网站上线的时间不长,访问量不是很大, ...
- C 基于UDP实现一个简易的聊天室
引言 本文是围绕Linux udp api 构建一个简易的多人聊天室.重点看思路,帮助我们加深 对udp开发中一些api了解.相对而言udp socket开发相比tcp socket开发注意的细节要少 ...
- C++开发的基于TCP协议的内网聊天工具
项目相关地址 源码:https://github.com/easonjim/TCPChat bug提交:https://github.com/easonjim/TCPChat/issues
- Pilin —— 一个基于Xmpp openfire smack的即时聊天工具
https://github.com/whfcomm/Pilin
- 基于Qt的P2P局域网聊天及文件传送软件设计
基于Qt的P2P局域网聊天及文件传送软件设计 zouxy09@qq.com http://blog.csdn.net/zouxy09 这是我的<通信网络>的课程设计作业,之 ...
- 基于UDP协议的控制台聊天
这几天学了java的网络编程弄出一个基于UDP协议的聊天工具 功能 添加并且备注好友(输入对方的ip) 删除好友 查看好友列表 用java写的控制台程序导出可执行程序后不能双击打开 还需要些一个脚本文 ...
- 与众不同 windows phone (31) - Communication(通信)之基于 Socket UDP 开发一个多人聊天室
原文:与众不同 windows phone (31) - Communication(通信)之基于 Socket UDP 开发一个多人聊天室 [索引页][源码下载] 与众不同 windows phon ...
随机推荐
- win10 下安装、配置、启动mysql
1.下载http://dev.mysql.com/downloads/mysql/ 2.Community > MySQL Community Server 3.Other Downloads: ...
- html5 app图片预加载
function Laimgload(){} //图片预加载JS Laimgload.prototype.winHeight = function(){ //计算页面高度 var winHeight ...
- oracle函数之replace
replace('将要更改的字符串','被替换掉的字符串','替换字符串'): ','****') from tmall_tcmessage; 输出为 '158****3367'
- Socket学习笔记
..........(此处略去万万字)学习中曲折的过程不介绍了,直接说结果 我的学习方法,问自己三个问题,学习过程将围绕这三个问题进行 what:socket是什么 why:为什么要使用socket ...
- C#调用C++的DLL 数据类型转换
/C++中的DLL函数原型为 //extern "C" __declspec(dllexport) bool 方法名一(const char* 变量名1, unsig ...
- hdu 1234
Problem Description 每天第一个到机房的人要把门打开,最后一个离开的人要把门关好.现有一堆杂乱的机房签 到.签离记录,请根据记录找出当天开门和关门的人. Input 测试输入的第一行 ...
- 将HTML格式的String转化为HTMLElement
代码如下: <meta charset="UTF-8"> <title>Insert title here</title> </head& ...
- 多路查找树之2-3-4树和B树 - 数据结构和算法82
多路查找树之2-3-4树和B树 让编程改变世界 Change the world by program 由2-3树到2-3-4树 ...... 省略,具体请看视频讲解 ...... B树 一个m阶的B ...
- 如何实现SQL事务的提交,又不对外进行污染
一.以下是本人的一点思路: 1.在事务方法中,参数运用委托Func,选用Func 的原因是多入参,单一出参2.事务传参运用泛型,选用泛型的原因是可以减少代码量,类型安全 二.说明中涉及4个类:1.Or ...
- 下一代云计算模式:Docker正掀起个性化商业革命
作者: 吴宁川 来源: ITValue 发布时间: 2015-09-20 10:41 阅读: 10008 次 推荐: 16 原文链接 [收藏] 文/ITValue 记者吴宁川 从 20 ...