用C#编写网络电话

来源:互联网 发布:程序员 出差吗 编辑:程序博客网 时间:2024/04/29 14:41
摘要:语音通话已经是IM的基本功能了,qq,MSN甚至连刚出来的百度HI都自带语音聊天的功能,大家可能觉得很炫,其实大家都是用的windows平台上的API,懂了原理之后自己也可以做,再说了微软也提供了DirectSound的托管互操作程序集,使.net开发人员也很容易的介入到这个领域,甚至你还可以写一个能跑在window mobile上的语音电话,现在好多手机都支持wifi,这样一个简单的wifi电话就由你的手里诞生了。本帖来和大家一起看看如何来做网络电话。

思路:要想做一个网络电话,基本遵循以下步骤
1、一方实时的录音,把模拟信号转换成数字信号;
2、把声音实时压缩
3、通过网络协议把压缩后的数据传输给接收方;
4、接收方解压缩接受到的音频数据;
5、实时的把接收到的数字信号转换成模拟信号并播放出来。

下面我们来看看每一步面临的挑战及其解决方案。
1、第一步,实时录音,DirectxSound有录音方面的API,托管的类分别是Microsoft.DirectX.DirectSound.CaptureDevicesCollection,Microsoft.DirectX.DirectSound.Capture和Microsoft.DirectX.DirectSound.CaptureBuffer,CaptureDevicesCollection用来枚举本机的可用的录音设备,Capture则表示一个录音设备,CaptureBuffer是用来存放录音数据的缓冲区,我们开始录音后,音频数据会不断的写入到环形的流式缓冲区,然后我们定期从缓冲区中把录音数据取出来返回给上层应用层就可以了。关于环形的流式缓冲区,可以看参考链接部分。

2、声音的压缩是一个很难抉择的步骤,默认的DirectSound只能播放和录制PCM格式(WAV)的音频数据,但这种声音格式特别大。常用的声音压缩格式有h.7231,gsm,amr,h.711等等,各种压缩算法都有自己的码率和适用范围。因为我们做的是互联网的语音电话,不考虑慢速网络和无线连接下的情况,也不用考虑终端设备的CPU能不能支持我们选用的压缩算法,我们做的语音电话双方都是PC机,应该什么解压缩算法都不会引起什么性能上的问题,所以只要网络快一些,选择哪个压缩算法都无所谓了,网上有h.711的压缩算法,我打算就采用这个,他的码率是64Kbps,比PCM的1.544Mbps和2.048Mbps要小的多。然后我们进行了音频数据压缩后,还可以对字节流进行GZIP或者7ZIP压缩,前者用SharpZip,后者7zip的官方有c#的使用代码,大家可以测试一下这两个算法的性能后做出适合自己的决定。关于各种压缩格式的特性可以参考我做的PPT及提供的参考链接。

3、网络电话注重实时性,而把声音从网络上传输就要走IP网络,而IP网络不是一个等时系统,所以我们就要尽量的去模拟实时的语音传输,提到实时,肯定UDP比TCP要实时,因为TCP要保证传输的可靠性,有序性等,而专门用于实时传输有一个应用层协议是RTP协议,这个协议一般就是建立在UDP基础上的,它在每个包头提供了一些序列号、时间戳等信息,但UDP本身并不会使用这些信息,这时候就有一个RTCP协议来用这些信息进行流量控制和拥塞控制,比如说RTCP检测到网络拥挤,会告诉发送方变换一种低码率的语音压缩算法来传输数据。这些大多都需要自己去实现,本文的源码没有去实现这些,关于RTP和RTCP可以参考相关资料或者我做的PPT。

4、每个压缩算法都有相应的解压缩算法,呵呵。

5、播放声音肯定也需要用到DS,也需要用到StreamBuffer,大致流程如下
1)创建一个声音设备Microsoft.DirectX.DirectSound.Device dev = new Microsoft.DirectX.DirectSound.Device();
2)设置协调级别dev.SetCooperativeLevel(this, Microsoft.DirectX.DirectSound.CooperativeLevel.Normal);
3)创建声音格式、缓冲区描述、及辅助缓冲区;
4)给辅助缓冲区设定通知;
5)用声音数据填满缓冲区;
6)播放缓冲区的声音数据,播放到一定的通知点,通知填充线程,填充新的声音数据;
7)循环第6步,直到没有新的声音数据填充到缓冲区。

具体的过程参考PPT或者具体代码。

版权声明:
附件源代码里的CaptureSound,SoundPlayer和CircularBuffer类反编译自随意桌面的代码(注释是我加的),版权归作者所有。

PPT里的图片和一些文字选自一个叫做ch11-DxSound&Input2.ppt的文件,源链接已丢失,还有一些选择一个叫做“SIP之 穿越NAT.ppt”的文件,网上可以搜索到,版权均归原作者所有,源作者要是再引用别人的东西,我就不知道了。

下面看一些具体的代码
用户创建声音格式

  1. public class DirectSoundManager
  2. {
  3.     public static WaveFormat CreateWaveFormat(int hz, short bits, short channels)
  4.     {
  5.         WaveFormat format = new WaveFormat();
  6.         //声音的格式,通常使用WAVE_FORMAT_PCM来设定,
  7.         //因为PCM是比较常用的声音格式。
  8.         format.FormatTag = WaveFormatTag.Pcm;
  9.         //采样率(单位:赫兹)典型值:11025、22050、44100Hz
  10.         format.SamplesPerSecond = hz;
  11.         //每个采样点数;8-bit或16-bit;
  12.         format.BitsPerSample = bits;
  13.         //声道的设置,当其值为1时是单声道,为2时是双声道;
  14.         format.Channels = channels;
  15.         //每个采样点字节数
  16.         format.BlockAlign = (short)(format.Channels * (format.BitsPerSample / 8));
  17.         //平均传输率,每秒的数据流量
  18.         format.AverageBytesPerSecond = format.BlockAlign * format.SamplesPerSecond;
  19.         return format;
  20.     }
  21.     属性#region 属性
  22.     // Properties
  23.     public static WaveFormat DefaultFormat
  24.     {
  25.         get
  26.         {
  27.             return WaveFormat_8000_8_1;
  28.         }
  29.     }
  30.     public static WaveFormat WaveFormat_11025_8_1
  31.     {
  32.         get
  33.         {
  34.             return CreateWaveFormat(0x2b11, 8, 1);
  35.         }
  36.     }
  37.     public static WaveFormat WaveFormat_22050_16_2
  38.     {
  39.         get
  40.         {
  41.             return CreateWaveFormat(0x5622, 0x10, 2);
  42.         }
  43.     }
  44.     public static WaveFormat WaveFormat_44100_16_2
  45.     {
  46.         get
  47.         {
  48.             return CreateWaveFormat(0xac44, 0x10, 2);
  49.         }
  50.     }
  51.     public static WaveFormat WaveFormat_8000_8_1
  52.     {
  53.         get
  54.         {
  55.             return CreateWaveFormat(0x1f40, 8, 1);
  56.         }
  57.     } 
  58.     #endregion
  59. }
复制代码
用于播放流式声音

  1. public class SoundPlayer : IDisposable
  2. {
  3.     私有成员#region 私有成员
  4.     private const int MaxLatencyMs = 300;
  5.     private const int NumberRecordNotifications = 4;
  6.     private readonly CircularBuffer circularBuffer;
  7.     private readonly int m_BufferBytes;
  8.     private readonly bool m_OwnsDevice;
  9.     private readonly int notifySize;
  10.     private readonly BufferPositionNotify[] positionNotify;
  11.     private bool isRunning;
  12.     private SecondaryBuffer m_Buffer;
  13.     private Device m_Device;
  14.     private int nextWriteOffset;
  15.     private AutoResetEvent notificationEvent;
  16.     private Notify notify;
  17.     private Thread notifyThread; 
  18.     #endregion
  19.     构造函数#region 构造函数
  20.     public SoundPlayer(Control owner, WaveFormat format)
  21.         : this(owner, null, format)
  22.     {
  23.     }
  24.     public SoundPlayer(Control owner, Device device, WaveFormat format)
  25.     {
  26.         positionNotify = new BufferPositionNotify[5];
  27.         notificationEvent = null;
  28.         notify = null;
  29.         notifyThread = null;
  30.         notifySize = 0;
  31.         m_Device = device;
  32.         if (m_Device == null)
  33.         {
  34.             m_Device = new Device();
  35.             m_Device.SetCooperativeLevel(owner, CooperativeLevel.Normal);
  36.             m_OwnsDevice = true;
  37.         }
  38.         // 设定通知的大小, 大小为播放一秒钟声音所需要的字节。这里为什么除以8,我不清楚
  39.         notifySize = (1024 > (format.AverageBytesPerSecond / 8)) ? (1024) : ((format.AverageBytesPerSecond / 8));
  40.         notifySize = (notifySize - (notifySize % format.BlockAlign));
  41.         m_BufferBytes = (notifySize * 4); //整体缓冲区的大小
  42.         BufferDescription desc = new BufferDescription(format);
  43.         //缓冲区具有控制音量的能力;
  44.         desc.ControlVolume = true;
  45.         //缓冲区具有控制位置的能力。
  46.         desc.ControlPositionNotify = true;
  47.         //设置缓冲区能取到当前的播放位置
  48.         desc.CanGetCurrentPosition = true;
  49.         //缓冲区不具有控制3D音效的能力;
  50.         desc.Control3D = false;
  51.         //Specifies whether the buffer supports effects processing.
  52.         desc.ControlEffects = false;
  53.         //缓冲区具有控制频率的能力;
  54.         desc.ControlFrequency = true;
  55.         //缓冲区具有控制左右声道的能力;
  56.         desc.ControlPan = true;
  57.         //设置是否使用全局缓存
  58.         desc.GlobalFocus = true;
  59.         //设置缓冲区大小为整个缓冲区的大小
  60.         desc.BufferBytes = m_BufferBytes;
  61.         //创建辅助缓冲区
  62.         m_Buffer = new SecondaryBuffer(desc, m_Device);
  63.         //创建环形缓冲区
  64.         circularBuffer = new CircularBuffer((m_BufferBytes * 10));
  65.         InitNotifications();
  66.         m_Buffer.Play(0, BufferPlayFlags.Looping);
  67.     }
  68.     public SoundPlayer(Control owner, int sr, short bps, short ch)
  69.         : this(owner, null, DirectSoundManager.CreateWaveFormat(sr, bps, ch))
  70.     {
  71.     }
  72.     public SoundPlayer(Control owner, Device device, int sr, short bps, short ch)
  73.         : this(owner, device, DirectSoundManager.CreateWaveFormat(sr, bps, ch))
  74.     {
  75.     } 
  76.     #endregion
  77.     公开属性#region 公开属性
  78.     public int BitsPerSample
  79.     {
  80.         get { return m_Buffer.Format.BitsPerSample; }
  81.     }
  82.     public int Channels
  83.     {
  84.         get { return m_Buffer.Format.Channels; }
  85.     }
  86.     public Device Device
  87.     {
  88.         get { return m_Device; }
  89.     }
  90.     public int SamplingRate
  91.     {
  92.         get { return m_Buffer.Format.SamplesPerSecond; }
  93.     } 
  94.     #endregion
  95.     IDisposable Members#region IDisposable Members
  96.     public void Dispose()
  97.     {
  98.         Stop();
  99.         if (m_Buffer != null)
  100.         {
  101.             m_Buffer.Dispose();
  102.             m_Buffer = null;
  103.         }
  104.         if (m_OwnsDevice && (m_Device != null))
  105.         {
  106.             m_Device.Dispose();
  107.             m_Device = null;
  108.         }
  109.         GC.SuppressFinalize(this);
  110.     }
  111.     ~SoundPlayer()
  112.     {
  113.         Dispose();
  114.     }
  115.     #endregion
  116.     私有方法#region 私有方法
  117.     private void InitNotifications()
  118.     {
  119.         notifyThread = new Thread(NotifyThreadHandler);
  120.         isRunning = true;
  121.         notifyThread.IsBackground = true;
  122.         notifyThread.Start();
  123.         notificationEvent = new AutoResetEvent(false);
  124.         notify = new Notify(m_Buffer);
  125.         //把整个缓冲区分成4个缓冲区片段,每播放4分之一就会给写线程发送一个信号
  126.         for (int i = 0; i < 4; i = (i + 1))
  127.         {
  128.             positionNotify[i].Offset = (((notifySize * i) + notifySize) - 1);
  129.             positionNotify[i].EventNotifyHandle = notificationEvent.SafeWaitHandle.DangerousGetHandle();
  130.         }
  131.         notify.SetNotificationPositions(positionNotify, 4);
  132.         nextWriteOffset = 0;
  133.     }
  134.     private void NotifyThreadHandler()
  135.     {
  136.         while (isRunning)
  137.         {
  138.             try
  139.             {
  140.                 notificationEvent.WaitOne(-1, true);
  141.                 Play();
  142.             }
  143.             catch (Exception)
  144.             {
  145.             }
  146.         }
  147.     }
  148.     private void Play()
  149.     {
  150.         try
  151.         {
  152.             try
  153.             {
  154.                 int currentPlayPosition;
  155.                 int currentWritePosition;
  156.                 m_Buffer.GetCurrentPosition(out currentPlayPosition, out currentWritePosition);
  157.                 //得到刚刚播放完的缓冲区片段,这个片段需要用新的数据去填充
  158.                 int lockSize = (currentWritePosition - nextWriteOffset);
  159.                 //todo:这里不知道什么时候会发生
  160.                 if (lockSize < 0)
  161.                 {
  162.                     lockSize = (lockSize + m_BufferBytes);
  163.                 }
  164.                 //对齐需要填充的缓冲区片段
  165.                 lockSize = (lockSize - (lockSize % notifySize));
  166.                 if (0 != lockSize)
  167.                 {
  168.                     if (lockSize == m_BufferBytes)
  169.                     {
  170.                     }
  171.                     byte[] data = new byte[lockSize];
  172.                     if (circularBuffer.Read(data) > 0)
  173.                     {
  174.                         m_Buffer.Write(nextWriteOffset, data, LockFlag.None);
  175.                         nextWriteOffset = (nextWriteOffset + lockSize);
  176.                         //如果完整写完一次缓冲区,那么把写数据指针放到缓冲区的最开始,
  177.                         //因为前面设置了m_Buffer.Play(0, BufferPlayFlags.Looping);
  178.                         //所以系统在播放缓冲区后会自动重新开始播放缓冲区起始处的声音数据
  179.                         nextWriteOffset = (nextWriteOffset % m_BufferBytes);
  180.                     }
  181.                 }
  182.             }
  183.             catch (Exception)
  184.             {
  185.             }
  186.         }
  187.         finally
  188.         {
  189.         }
  190.     } 
  191.     #endregion
  192.     公开方法#region 公开方法
  193.     public void Stop()
  194.     {
  195.         isRunning = false;
  196.         if (m_Buffer != null)
  197.         {
  198.             m_Buffer.Stop();
  199.         }
  200.     }
  201.     public void Write(byte[] data)
  202.     {
  203.         try
  204.         {
  205.             Console.WriteLine("播放声音:{0}", data.Length);
  206.             circularBuffer.Write(data);
  207.         }
  208.         catch (Exception)
  209.         {
  210.         }
  211.     } 
  212.     #endregion
  213. }
复制代码
用户录制声音

  1. public class CaptureSound
  2. {
  3.     私有成员#region 私有成员
  4.     private const int NumberRecordNotifications = 4;
  5.     private readonly BufferPositionNotify[] positionNotify;
  6.     private Capture selectedDevice;
  7.     private CaptureBuffer buffer;
  8.     private int captureBufferSize;
  9.     private string fileName;
  10.     private bool isRecording;
  11.     private int nextCaptureOffset;
  12.     private AutoResetEvent notificationEvent;
  13.     private Notify notify;
  14.     private int notifySize;
  15.     private Thread notifyThread;
  16.     private long sampleCount;
  17.     private WaveFormat selectedFormat;
  18.     private FileStream waveFile;
  19.     private BinaryWriter writer; 
  20.     #endregion
  21.     构造函数#region 构造函数
  22.     public CaptureSound()
  23.     {
  24.         isRecording = false;
  25.         positionNotify = new BufferPositionNotify[5];
  26.         notificationEvent = null;
  27.         buffer = null;
  28.         fileName = string.Empty;
  29.         notify = null;
  30.         notifyThread = null;
  31.         waveFile = null;
  32.         writer = null;
  33.         captureBufferSize = 0;
  34.         nextCaptureOffset = 0;
  35.         sampleCount = 0L;
  36.         notifySize = 0;
  37.         InitializeDeviceSelector();
  38.         InitializeWaveFormatSelector();
  39.         Initialize();
  40.     }
  41.     public CaptureSound(Capture device)
  42.     {
  43.         isRecording = false;
  44.         positionNotify = new BufferPositionNotify[5];
  45.         notificationEvent = null;
  46.         buffer = null;
  47.         fileName = string.Empty;
  48.         notify = null;
  49.         notifyThread = null;
  50.         waveFile = null;
  51.         writer = null;
  52.         captureBufferSize = 0;
  53.         nextCaptureOffset = 0;
  54.         sampleCount = 0L;
  55.         notifySize = 0;
  56.         selectedDevice = device;
  57.         InitializeWaveFormatSelector();
  58.         Initialize();
  59.     }
  60.     public CaptureSound(WaveFormat waveFormat)
  61.     {
  62.         isRecording = false;
  63.         positionNotify = new BufferPositionNotify[5];
  64.         notificationEvent = null;
  65.         buffer = null;
  66.         fileName = string.Empty;
  67.         notify = null;
  68.         notifyThread = null;
  69.         waveFile = null;
  70.         writer = null;
  71.         captureBufferSize = 0;
  72.         nextCaptureOffset = 0;
  73.         sampleCount = 0L;
  74.         notifySize = 0;
  75.         selectedFormat = waveFormat;
  76.         InitializeDeviceSelector();
  77.         Initialize();
  78.     }
  79.     public CaptureSound(Capture device, WaveFormat waveFormat)
  80.     {
  81.         isRecording = false;
  82.         positionNotify = new BufferPositionNotify[5];
  83.         notificationEvent = null;
  84.         buffer = null;
  85.         fileName = string.Empty;
  86.         notify = null;
  87.         notifyThread = null;
  88.         waveFile = null;
  89.         writer = null;
  90.         captureBufferSize = 0;
  91.         nextCaptureOffset = 0;
  92.         sampleCount = 0L;
  93.         notifySize = 0;
  94.         selectedDevice = device;
  95.         selectedFormat = waveFormat;
  96.         Initialize();
  97.     } 
  98.     #endregion
  99.     公开属性#region 公开属性
  100.     public int BufferBytes
  101.     {
  102.         get { return captureBufferSize; }
  103.     }
  104.     public string FileName
  105.     {
  106.         get { return fileName; }
  107.         set
  108.         {
  109.             fileName = value;
  110.             CreateRIFF();
  111.         }
  112.     }
  113.     public long SampleCount
  114.     {
  115.         get { return sampleCount; }
  116.     }
  117.     public WaveFormat SelectedFormat
  118.     {
  119.         get { return selectedFormat; }
  120.     } 
  121.     #endregion
  122.     公开事件#region 公开事件
  123.     public event DirectSoundBufferDataEventHandler BufferData; 
  124.     #endregion
  125.     私有方法#region 私有方法
  126.     private void CreateCaptureBuffer()
  127.     {
  128.         CaptureBufferDescription desc = new CaptureBufferDescription();
  129.         if (null != notify)
  130.         {
  131.             notify.Dispose();
  132.             notify = null;
  133.         }
  134.         if (null != buffer)
  135.         {
  136.             buffer.Dispose();
  137.             buffer = null;
  138.         }
  139.         if (0 != selectedFormat.Channels)
  140.         {
  141.             notifySize = (1024 > (selectedFormat.AverageBytesPerSecond / 8))
  142.                             ? (1024)
  143.                             :
  144.                                 ((selectedFormat.AverageBytesPerSecond / 8));
  145.             notifySize = (notifySize - (notifySize % selectedFormat.BlockAlign));
  146.             captureBufferSize = (notifySize * 4);
  147.             desc.BufferBytes = captureBufferSize;
  148.             selectedFormat.FormatTag = WaveFormatTag.Pcm;
  149.             desc.Format = selectedFormat;
  150.             buffer = new CaptureBuffer(desc, selectedDevice);
  151.             nextCaptureOffset = 0;
  152.             InitNotifications();
  153.         }
  154.     }
  155.     private void CreateRIFF()
  156.     {
  157.         waveFile = new FileStream(FileName, FileMode.Create);
  158.         writer = new BinaryWriter(waveFile);
  159.         char[] chArray = new char[] { 'R', 'I', 'F', 'F' };
  160.         char[] chArray2 = new char[] { 'W', 'A', 'V', 'E' };
  161.         char[] chArray3 = new char[] { 'f', 'm', 't', ' ' };
  162.         char[] chArray4 = new char[] { 'd', 'a', 't', 'a' };
  163.         short num = 1;
  164.         int num2 = 0x10;
  165.         int num3 = 0;
  166.         short num4 = 0;
  167.         if ((8 == selectedFormat.BitsPerSample) && (1 == selectedFormat.Channels))
  168.         {
  169.             num4 = 1;
  170.         }
  171.         else if (((8 == selectedFormat.BitsPerSample) && (2 == selectedFormat.Channels)) ||
  172.                 ((0x10 == selectedFormat.BitsPerSample) && (1 == selectedFormat.Channels)))
  173.         {
  174.             num4 = 2;
  175.         }
  176.         else if ((0x10 == selectedFormat.BitsPerSample) && (2 == selectedFormat.Channels))
  177.         {
  178.             num4 = 4;
  179.         }
  180.         writer.Write(chArray);
  181.         writer.Write(num3);
  182.         writer.Write(chArray2);
  183.         writer.Write(chArray3);
  184.         writer.Write(num2);
  185.         writer.Write(num);
  186.         writer.Write(selectedFormat.Channels);
  187.         writer.Write(selectedFormat.SamplesPerSecond);
  188.         writer.Write(selectedFormat.AverageBytesPerSecond);
  189.         writer.Write(num4);
  190.         writer.Write(selectedFormat.BitsPerSample);
  191.         writer.Write(chArray4);
  192.         writer.Write(0);
  193.     }
  194.     private void Initialize()
  195.     {
  196.         CreateCaptureBuffer();
  197.     }
  198.     private void InitializeDeviceSelector()
  199.     {
  200.         CaptureDevicesCollection devices = new CaptureDevicesCollection();  // 枚举音频捕捉设备 
  201.         if (devices.Count > 0)
  202.             selectedDevice = new Capture(devices[0].DriverGuid);
  203.         else
  204.             throw new ArgumentException("无法初始化声音设备");
  205.     }
  206.     private void InitializeWaveFormatSelector()
  207.     {
  208.         if (selectedDevice == null)
  209.         {
  210.             throw new ArgumentException("尚未設定音訊裝置,無法選擇輸出格式。");
  211.         }
  212.         selectedFormat = DirectSoundManager.DefaultFormat;
  213.     }
  214.     private void InitNotifications()
  215.     {
  216.         if (null == buffer)
  217.         {
  218.             throw new NullReferenceException();
  219.         }
  220.         if (null == notifyThread)
  221.         {
  222.             isRecording = true;
  223.             notifyThread = new Thread(WaitThread);
  224.             notifyThread.IsBackground = true;
  225.             notifyThread.Start();
  226.             notificationEvent = new AutoResetEvent(false);
  227.         }
  228.         for (int i = 0; i < 4; i++)
  229.         {
  230.             positionNotify[i].Offset = (((notifySize * i) + notifySize) - 1);
  231.             positionNotify[i].EventNotifyHandle = notificationEvent.SafeWaitHandle.DangerousGetHandle();
  232.         }
  233.         notify = new Notify(buffer);
  234.         notify.SetNotificationPositions(positionNotify, 4);
  235.     }
  236.     private void OnBufferData(object sender, DirectSoundBufferDataEventArgs e)
  237.     {
  238.         if (BufferData != null)
  239.         {
  240.             BufferData(sender, e);
  241.         }
  242.     }
  243.     private void RecordCapturedData()
  244.     {
  245.         byte[] data = null;
  246.         try
  247.         {
  248.             try
  249.             {
  250.                 int currentPlayPosition;
  251.                 int currentWritePosition;
  252.                 buffer.GetCurrentPosition(out currentWritePosition, out currentPlayPosition);
  253.                 int lockSize = (currentPlayPosition - nextCaptureOffset);
  254.                 if (lockSize < 0)
  255.                 {
  256.                     lockSize = (lockSize + captureBufferSize);
  257.                 }
  258.                 lockSize = (lockSize - (lockSize % notifySize));
  259.                 if (0 != lockSize)
  260.                 {
  261.                     data = (byte[])buffer.Read(nextCaptureOffset, typeof(byte), LockFlag.None, new int[] { lockSize });
  262.                     OnBufferData(this, new DirectSoundBufferDataEventArgs(data));
  263.                     if (writer != null)
  264.                     {
  265.                         writer.Write(data, 0, data.Length);
  266.                     }
  267.                     sampleCount = (sampleCount + data.Length);
  268.                     nextCaptureOffset = (nextCaptureOffset + data.Length);
  269.                     nextCaptureOffset = (nextCaptureOffset % captureBufferSize);
  270.                 }
  271.             }
  272.             catch (Exception)
  273.             {
  274.             }
  275.         }
  276.         finally
  277.         {
  278.             data = null;
  279.         }
  280.     }
  281.     private void WaitThread()
  282.     {
  283.         while (isRecording)
  284.         {
  285.             try
  286.             {
  287.                 notificationEvent.WaitOne(-1, true);
  288.                 RecordCapturedData();
  289.             }
  290.             catch (Exception)
  291.             {
  292.             }
  293.         }
  294.     }
  295.     private void StartOrStopRecord(bool StartRecording)
  296.     {
  297.         if (StartRecording)
  298.         {
  299.             isRecording = true;
  300.             CreateCaptureBuffer();
  301.             buffer.Start(true);
  302.         }
  303.         else
  304.         {
  305.             isRecording = false;
  306.             buffer.Stop();
  307.             RecordCapturedData();
  308.             if (writer != null)
  309.             {
  310.                 writer.Seek(4, SeekOrigin.Begin);
  311.                 writer.Write(((int)(sampleCount + 0x24L)));
  312.                 writer.Seek(40, SeekOrigin.Begin);
  313.                 writer.Write(sampleCount);
  314.                 writer.Close();
  315.                 writer = null;
  316.                 waveFile = null;
  317.             }
  318.         }
  319.     }
  320.     #endregion
  321.     公开方法#region 公开方法
  322.     public void Pause()
  323.     {
  324.         buffer.Stop();
  325.     }
  326.     public void Resume()
  327.     {
  328.         buffer.Start(true);
  329.     }
  330.     public void Start()
  331.     {
  332.         StartOrStopRecord(true);
  333.     }
  334.     public void Stop()
  335.     {
  336.         StartOrStopRecord(false);
  337.         notifyThread = null;
  338.         nextCaptureOffset = 0;
  339.         sampleCount = 0L;
  340.     } 
  341.     #endregion
  342. }
复制代码
参考链接如下:

ch11-DxSound&Input2.ppt:建立DirectSound 声音的播放与控制 使用3D音效

demo   http://u.115.com/file/clviphqj#
用C#编写网络电话.rar