C#播放声音【六种方法】

C#中声音的播放主要有六种方法:
1.播放系统事件声音 
2.使用SoundPlayer
3.使用API函数播放
4.使用axWindowsMediaPlayer的COM组件来播放
5.Microsoft speech object Library

6.使用directX


1.播放系统事件声音 

  1. System.Media.SystemSounds.Asterisk.Play();
  2. System.Media.SystemSounds.Beep.Play();
  3. System.Media.SystemSounds.Exclamation.Play();
  4. System.Media.SystemSounds.Hand.Play();
  5. System.Media.SystemSounds.Question.Play();


2. 使用SoundPlayer
  1. SoundPlayer player = new SoundPlayer();
  2. player.SoundLocation = @"D:\test.wav";
  3. player.Load(); //同步加载声音
  4. player.Play(); //启用新线程播放
  5. //player.PlayLooping(); //循环播放模式
  6. //player.PlaySync(); //UI线程同步播放


3. 使用API函数播放

  1. using System.Runtime.InteropServices;
  2. public static class WavPlayer
  3. {
  4. [DllImport("winmm.dll", SetLastError = true)]
  5. static extern bool PlaySound(string pszSound, UIntPtr hmod, uint fdwSound);
  6. [DllImport("winmm.dll", SetLastError = true)]
  7. static extern long mciSendString(string strCommand,
  8. StringBuilder strReturn,int iReturnLength, IntPtr hwndCallback);
  9. [DllImport("winmm.dll")]
  10. private static extern long sndPlaySound(string lpszSoundName, long uFlags);
  11. [Flags]
  12. public enum SoundFlags
  13. {
  14. /// <summary>play synchronously (default) </summary>
  15. SND_SYNC = 0x0000,
  16. /// <summary>play asynchronously </summary>
  17. SND_ASYNC = 0x0001,
  18. /// <summary>silence (!default) if sound not found </summary>
  19. SND_NODEFAULT = 0x0002,
  20. /// <summary>pszSound points to a memory file </summary>
  21. SND_MEMORY = 0x0004,
  22. /// <summary>loop the sound until next sndPlaySound </summary>
  23. SND_LOOP = 0x0008,
  24. /// <summary>don’t stop any currently playing sound </summary>
  25. SND_NOSTOP = 0x0010,
  26. /// <summary>Stop Playing Wave </summary>
  27. SND_PURGE = 0x40,
  28. /// <summary>don’t wait if the driver is busy </summary>
  29. SND_NOWAIT = 0x00002000,
  30. /// <summary>name is a registry alias </summary>
  31. SND_ALIAS = 0x00010000,
  32. /// <summary>alias is a predefined id </summary>
  33. SND_ALIAS_ID = 0x00110000,
  34. /// <summary>name is file name </summary>
  35. SND_FILENAME = 0x00020000,
  36. /// <summary>name is resource name or atom </summary>
  37. SND_RESOURCE = 0x00040004
  38. }
  39. public static void Play(string strFileName)
  40. {
  41. PlaySound(strFileName, UIntPtr.Zero,
  42. (uint)(SoundFlags.SND_FILENAME | SoundFlags.SND_SYNC | SoundFlags.SND_NOSTOP));
  43. }
  44. public static void mciPlay(string strFileName)
  45. {
  46. string playCommand = "open " + strFileName + " type WAVEAudio alias MyWav";
  47. mciSendString(playCommand, null, 0, IntPtr.Zero);
  48. mciSendString("play MyWav", null, 0, IntPtr.Zero);
  49. }
  50. public static void sndPlay(string strFileName)
  51. {
  52. sndPlaySound(strFileName, (long)SoundFlags.SND_SYNC);
  53. }
  54. }
关于mciSendString的详细参数说明,请参见MSDN,或是http://blog.csdn.net/psongchao/archive/2007/01/19/1487788.aspx


4.使用axWindowsMediaPlayer的COM组件来播放


选择菜单中的“工具”中的“自定义工具箱(添加/移除工具箱项)”,在自定义工具箱的窗口中,点击展开“COM 组件”项,选中“WindowMedia Player”选项。确定后在“工具箱”中便会出现“Windows Media Player”这一项,然后再将其拖至Form上,调整大小,系统在“引用”中自动加入了对此dll的引用,AxMediaPlayer就是我们使用的 Namespace与class。

把Windows Media Player控件拖放到Winform窗体中,把axWindowsMediaPlayer1中URL属性设置为MP3或是AVI的文件路径。

  1. private voidmenuItem1_Click(object sender, System.EventArgs e)
  2. {
  3. OpenFileDialogofDialog = new OpenFileDialog();
  4. ofDialog.AddExtension= true;
  5. ofDialog.CheckFileExists= true;
  6. ofDialog.CheckPathExists= true;
  7. //the nextsentence must be in single line
  8. ofDialog.Filter= "VCD文件(*.dat)|*.dat|Audio文件(*.avi)|*.avi
  9. |WAV文件(*.wav)|*.wav|MP3文件(*.mp3)|*.mp3|所有文件 (*.*)|*.*";
  10. ofDialog.DefaultExt= "*.mp3";
  11. if(ofDialog.ShowDialog()== DialogResult.OK)
  12. {
  13. // 2003一下版本 方法this.axMediaPlayer1.FileName = ofDialog.FileName;
  14. this.axMediaPlayer1.URL=ofDialog.FileName;//2005用法
  15. }
  16. }

5.Microsoft speech object Library

  1. /// <summary
  2. /// 播放声音文件
  3. /// </summary>
  4. /// <paramname="FileName">文件全名 </param>
  5. public voidPlaySound(string FileName)
  6. {//要加载COM组件:Microsoft speech object Library
  7. if (!System.IO.File.Exists(FileName))
  8. {
  9. return;
  10. }
  11. SpeechLib.SpVoiceClass pp = new SpeechLib.SpVoiceClass();
  12. SpeechLib.SpFileStreamClass spFs = new SpeechLib.SpFileStreamClass();
  13. spFs.Open(FileName, SpeechLib.SpeechStreamFileMode.SSFMOpenForRead,true);
  14. SpeechLib.ISpeechBaseStream Istream = spFs as SpeechLib.ISpeechBaseStream;
  15. pp.SpeakStream(Istream, SpeechLib.SpeechVoiceSpeakFlags.SVSFIsFilename);
  16. spFs.Close();
  17. }


6.  使用directX

准备工作:

  1.安装了DirectX SDK(有9个DLL文件)。这里我们只用到MicroSoft.DirectX.dll 和 Microsoft.Directx.DirectSound.dll

  2.一个W***文件。(这样的文件比较好找,在QQ的目录里就不少啊。这里就不多说了。)名字叫SND.W***,放在最后目标程序的同个目录下面

  开始写程序啦。随便用个UltraEdit就好了。

  1.引入DirectX 的DLL文件的名字空间:

using Microsoft.DirectX;
using Microsoft.DirectX.DirectSound;

  2.建立设备。在我们导入的Microsoft.DirectX.DirectSound空间中,有个Device的类。这个是表示系统中的声音设备。

Device dv=new Device();

  3.设置CooperativeLevel。因为windows是多任务的系统,设备不是独占的,所以在使用设备前要为这个设备设置CooperativeLevel。调用Device的SetCooperativeLevel方法:其中,第一个参数是一个Control,第二个参数是个枚举类型。

  在这个程序中,Control我随便弄了个参数塞进去(很汗吧!)。如果在windows程序中,可以用this代替。第二个参数就是优先级别,这里表示优先播放。 

dv.SetCooperativeLevel((new UF()),CooperativeLevel.Priority);

  4.开辟缓冲区。对于上面的声音设备,他有个自己的缓冲区,叫主缓冲区。系统中,一个设备有唯一的主缓冲区。由于windows是多任务(又是这个!),所以可以有几个程序同时利用一个设备播放声音,所以每个程序都自己开辟一个二级缓冲区,放自己的声音。

  系统根据各个程序的优先级别,按照相应的顺序分别去各个二级缓冲区中读取内容到主缓冲区中播放。这里,我们为SND.W***开辟一个缓冲区。

  其中,第一个参数表示文件名(傻瓜都看出来了!),第二个就是需要使用的设备。

SecondaryBuffer buf=new SecondaryBuffer(@"snd.wav",dv);

  5.接下来就可以播放啦。第一个参数表示优先级别,0是最低的。第2个参数是播放方式,这里是循环播放。

buf.Play(0,BufferPlayFlags.Looping);

  6.由于命令行程序没有消息循环,执行完代码就退出了,所以,我们需要暂停程序。

Console.Read();

  7.关键的部分已经完了,这里只是交代一下刚才的那个倒霉的new UF() 是什么东西。这个完全是为了应付SetCooperativeLevel的参数要求。我不知道这样做有什么附作用(各位如果因此把声卡烧了…………)

class UF:Form{}

  8.代码写完啦~~~。下面可以编译了,这里编译比较复杂点。

csc /r:directX/MicroSoft.DirectX.dll;directX/Microsoft.Directx.DirectSound.dll dxsnd.cs

  这里,我把2个DLL文件放在当前目录的directx目录下(这个是我自己建的,你只需要指出这2个文件的位置就可以了。)

  顺便把我的目录结构说明一下:

|
|--dxsnd.cs
|--snd.wav
|--<directx>
|
|--MicroSoft.DirectX.dll
|--Microsoft.Directx.dll

  下面是完整代码:

//dxsnd.cs
using System;
using Microsoft.DirectX;
using Microsoft.DirectX.DirectSound;
using System.Windows.Forms;
namespace test1
{
 class test
 {
  public static void Main(string [] args)
  {
   Device dv=new Device();
   dv.SetCooperativeLevel((new UF()),CooperativeLevel.Priority);
   SecondaryBuffer buf=new SecondaryBuffer(@"snd.wav",dv);
   buf.Play(0,BufferPlayFlags.Looping);
   Console.ReadLine();
  }
  class UF:Form{}
 }
}


参考:http://blog.csdn.net/holyrong/article/details/1748500

    http://www.cnblogs.com/net-study/archive/2013/07/10/3181674.html

    http://www.sufeinet.com/thread-459-1-1.html

转自:https://blog.csdn.net/wangzhen209/article/details/53285651

猜你喜欢

转载自blog.csdn.net/lbc2100/article/details/80923975
今日推荐