1.在C#中有很多方法播放声音,可以直接调用Beep()和MessageBeep()方法(在System.Console命名空间里)来播放Windows扬声器的提示声音。也可以调用PlaySound()来播放,用法如下:
using System;
using System.Runtime.InteropServices;
[DllImport("winmm.dll")]
public static extern bool PlaySound(string pszSound, int hmod, int fdwSound);//播放windows音乐,重载
public const int SND_FILENAME = 0x00020000;
public const int SND_ASYNC = 0x0001;
上面的方法有个缺陷,就是只能播放绝对路径的声音文件,如果想在项目中加入音频文件来播放的话,可以用一个方法来获取项目的目录路径,然后再把音频文件放在这个路径的下面。这是我做的项目中的一段代码:
获取当前项目路径的方法可用下文的方法:
http://blog.csdn.net/holyrong/archive/2007/08/21/1752672.aspx
2.另一种方法是利用DerectX控件,下面引用网上一位朋友的文章:
准备工作:
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; |
Device dv=new Device(); |
dv.SetCooperativeLevel((new UF()),CooperativeLevel.Priority); |
SecondaryBuffer buf=new SecondaryBuffer(@"snd.wav",dv); |
buf.Play(0,BufferPlayFlags.Looping); |
Console.Read(); |
class UF:Form{} |
csc /r:directX/MicroSoft.DirectX.dll;directX/Microsoft.Directx.DirectSound.dll dxsnd.cs |
//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{} } } |