C#播放声音的四种方法.docx
《C#播放声音的四种方法.docx》由会员分享,可在线阅读,更多相关《C#播放声音的四种方法.docx(31页珍藏版)》请在冰豆网上搜索。
C#播放声音的四种方法
C#播放声音的四种方法
C#播放声音的四种方法
介绍之前首先推荐一个程序员专用搜索引擎-
第一种是利用DirectX
1.安装了DirectXSDK(有9个DLL文件)。
这里我们只用到MicroSoft.DirectX.dll和Microsoft.Directx.DirectSound.dll
2.引入DirectX的DLL文件的名字空间:
usingMicrosoft.DirectX;
usingMicrosoft.DirectX.DirectSound;
3.建立设备
Devicedv=newDevice();
4.设置CooperativeLevel。
因为windows是多任务的系统,设备不是独占的
SecondaryBufferbuf=newSecondaryBuffer(@"snd.wav",dv);
5.开辟缓冲区SecondaryBufferbuf=newSecondaryBuffer(@"snd.wav",dv);
6.接下来就可以播放啦。
第一个参数表示优先级别,0是最低的。
第2个参数是播放方式,这里是循环播放。
buf.Play(0,BufferPlayFlags.Looping);
第二种是利用MicrosoftspeechobjectLibrary
//////播放声音文件
///
///文件全名
publicvoidPlaySound(stringFileName)
{//要加载COM组件:
MicrosoftspeechobjectLibrary
if(!
System.IO.File.Exists(FileName))
{
return;
}
SpeechLib.SpVoiceClasspp=newSpeechLib.SpVoiceClass();
SpeechLib.SpFileStreamClassspFs=newSpeechLib.SpFileStreamClass();
spFs.Open(FileName,SpeechLib.SpeechStreamFileMode.SSFMOpenForRead,true);
SpeechLib.ISpeechBaseStreamIstream=spFsasSpeechLib.ISpeechBaseStream;
pp.SpeakStream(Istream,SpeechLib.SpeechVoiceSpeakFlags.SVSFIsFilename);
spFs.Close();
}
第三种:
引用SoundPlayer
System.Media.SoundPlayersndPlayer=newSystem.Media.SoundPlayer(Application.StartupPath+@"/pm3.wav");
sndPlayer.PlayLooping();
第4种:
利用WindowsMediaPlayer
新建一个C#的WindowsForm工程(Windows应用程序),并且定义两个菜单按钮(menuItem1,menuItem2)。
选择菜单中的“工具”中的“自定义工具箱(添加/移除工具箱项)”,在自定义工具箱的窗口中,点击展开“COM组件”项,选中“WindowMediaPlayer”选项。
确定后在“工具箱”中便会出现“WindowsMediaPlayer”这一项,然后再将其拖至Form上,调整大小,系统在“引用”中自动加入了对此dll的引用,AxMediaPlayer就是我们使用的Namespace与class。
在属性栏中设置好此控件的一些属性,为了方便,这里我把AutoStart设置成为true(其实默认是true),只要FileName被设置(打开了文件),则文件将会自动播放。
完整代码如下:
privatevoidmenuItem1_Click(objectsender,System.EventArgse)
{
OpenFileDialogofDialog=newOpenFileDialog();
ofDialog.AddExtension=true;
ofDialog.CheckFileExists=true;
ofDialog.CheckPathExists=true;
//thenextsentencemustbeinsingleline
ofDialog.Filter="VCD文件(*.dat)|*.dat|Audio文件(*.avi)|*.avi
|WAV文件(*.wav)|*.wav|MP3文件(*.mp3)|*.mp3|所有文件(*.*)|*.*";
ofDialog.DefaultExt="*.mp3";
if(ofDialog.ShowDialog()==DialogResult.OK)
{
//2003一下版本方法this.axMediaPlayer1.FileName=ofDialog.FileName;
this.axMediaPlayer1.URL=ofDialog.FileName;//2005用法
}
}
这里使用的是微软的播放器,大家也可以试试Winamp的控件,如果你只需要播放声音而不需要显示,你只要把AxMediaPlayer的Visible属性设置为false就可以了。
//Sound.cs
//(c)CopyrightJasonClark2003
//Showsavarietyofbasicmarshallingconceptsbymakingsounds
usingSystem;
usingWintellect.Interop.Sound;
classApp{
publicstaticvoidMain(){
//ProduceanOKbeep
Sound.MessageBeep(BeepTypes.Ok);
System.Threading.Thread.Sleep(1000);
//Ok,nowforsomecirca-1977si-fi
Randomrand=newRandom();
for(Int32index=0;index<7;index++){
Sound.Beep(rand.Next(500)+1000,TimeSpan.FromSeconds(.10));
}
//Pickawave,anywave
Sound.PlayWave(@"C:
\WINDOWS\Media\BATTLOW.WAV",true);
System.Threading.Thread.Sleep(2000);
Sound.StopWave();
}
}
namespaceWintellect.Interop.Sound{
usingSystem.Runtime.InteropServices;
usingSystem.ComponentModel;
sealedclassSound{
//FriendlyMessageBeep()wrapper
publicstaticvoidMessageBeep(BeepTypestype){
if(!
MessageBeep((UInt32)type)){
Int32err=Marshal.GetLastWin32Error();
thrownewWin32Exception(err);
}
}
//Friendlylow-levelbeepwrapper
publicstaticvoidBeep(Int32frequency,Int32milliseconds){
if(!
UnmanagedBeep((UInt32)frequency,(UInt32)milliseconds)){
Int32err=Marshal.GetLastWin32Error();
thrownewWin32Exception(err);
}
}
//Friendlylow-levelbeepwrapperwithTimeSpan
publicstaticvoidBeep(Int32frequency,TimeSpanduration){
Beep(frequency,(Int32)duration.TotalMilliseconds);
}
//FriendlyPlaySound()wrapperforplayingwavefiles
publicstaticvoidPlayWave(Stringfilename,Booleanlooped){
UInt32flags=sndAsyncFlag|sndFilenameFlag;
if(looped)flags|=sndLoopFlag;
if(!
PlaySound(filename,IntPtr.Zero,flags)){
Int32err=Marshal.GetLastWin32Error();
thrownewWin32Exception(err);
}
}
//FriendlyPlaySound()wrapperforplayingwavefiles
publicstaticvoidPlayWave(Stringfilename){
PlayWave(filename,false);
}
//FriendlyPlaySound()wrapperforstoppingwavefiles
publicstaticvoidStopWave(){
PlayWave(null);
}
//staticexternmethodsformakingsoundthroughinterop
[DllImport("User32.dll",SetLastError=true)]
staticexternBooleanMessageBeep(UInt32beepType);
[DllImport("Kernel32.dll",EntryPoint="Beep",SetLastError=true)]
staticexternBooleanUnmanagedBeep(UInt32frequency,UInt32duration);
[DllImport("Winmm.dll",CharSet=CharSet.Auto,SetLastError=true)]
staticexternBooleanPlaySound(Stringfilename,
IntPtrmodule,UInt32flags);
//SomeprivatehelpervaluesforcallingPlaySound
constUInt32sndAsyncFlag=0x0001;
constUInt32sndLoopFlag=0x0008;
constUInt32sndFilenameFlag=0x00020000;
privateSound(){}
}
//Enumformessagebeeptypes
enumBeepTypes{
Simple=-1,
Ok=0x00000000,
IconHand=0x00000010,
IconQuestion=0x00000020,
IconExclamation=0x00000030,
IconAsterisk=0x00000040
}
}
[DllImport("Winmm.dll")]
public static extern long PlaySound(string name,long module,long flag);
[DllImport("winmm.dll")]
private static extern long mciSendString(string lpstrCommand,string lpstrReturnString,long length,long hwndcallback);
private string m_MusicName="";
private void PlayMusic()
{
m_MusicName="\""+Tool.ReadInfo("promptmusicfile")+"\"";
if(m_MusicName.Length==0)
return;
try
{
mciSendString(@"close " + m_MusicName," ",0,0);
mciSendString(@"open " + m_MusicName," ",0,0);
mciSendString(@"play " + m_MusicName ," ",0,0);
}
catch
{
}
}
private void StopMusic()
{
try
{
mciSendString(@"close " + m_MusicName," ",0,0);
}
catch{}
}
播放内存中的WAV文件可以这样:
//API定义
private const int SND_ASYNC = 0x1;
private const int SND_MEMORY = 0x4;
[DllImport("winmm.dll")]
private static extern int sndPlaySoundA(byte[] lpszSoundName, int uFlags);
//将blip1.wav添加入工程并设置为嵌入的资源
//现在是将它读入内存备用
Type t=this.GetType();
System.Reflection.Assembly a=t.Assembly;
System.IO.Stream stream=a.GetManifestResourceStream(t.Namespace+".blip1.wav");
byte[] ba=new byte[stream.Length];
stream.Read(ba,0, ba.Length);
stream.Close();
//播放缓存
sndPlaySoundA(ba, SND_MEMORY);
∙用API函数winmm下的PlaySound播放声音:
(一). 说明
一个播放音乐的类,要准备好自己的音乐文件,比如:
*.mid/*.wav等
(二).步骤
using System;
using System.Collections;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace 象棋游戏音效支持类
{
///
/// 用于播放音乐
///
internal class Helpers
{
[Flags]
public enum PlaySoundFlags :
int
{
SND_SYNC = 0x0000, /* play synchronously (default) */ //同步
SND_ASYNC = 0x0001, /* play asynchronously */ //异步
SND_NODEFAULT = 0x0002, /* silence (!
default) if sound not found */
SND_MEMORY = 0x0004, /* pszSound points to a memory file */
SND_LOOP = 0x0008, /* loop the sound until next sndPlaySound */
SND_NOSTOP = 0x0010, /* don't stop any currently playing sound */
SND_NOWAIT = 0x00002000, /* don't wait if the driver is busy */
SND_ALIAS = 0x00010000, /* name is a registry alias */
SND_ALIAS_ID = 0x00110000, /* alias is a predefined ID */
SND_FILENAME = 0x00020000, /* name is file name */
SND_RESOURCE = 0x00040004 /* name is resource name or atom */
}
[DllImport("winmm")]
public static extern bool PlaySound( string szSound, IntPtr hMod, PlaySoundFlags flags );
}
public class Sound
{
public static void Play( string strFileName )
{
switch(strFileName)
{
case "start":
strFileName=@"..\..\sound\start.WAV"; break;
case "back":
strFileName=@"..\..\sound\back.WAV"; break;
case "fall":
strFileName=@"..\..\sound\fall.WAV"; break;
case "huiqi":
strFileName=@"..\..\sound\huiqi.WAV"; break;
case "huiqiend":
strFileName=@"..\..\sound\huiqiend.WAV"; break;
case "jiangjun":
strFileName=@"..\..\sound\jiangjun.WAV"; break;
case "kill":
strFileName=@"..\..\sound\kill.WAV"; break;
case "win":
strFileName=@"..\..\sound\win.WAV"; break;
case "move":
strFileName=@"..\..\sound\move.WAV"; break;
case "hold":
strFileName=@"..\..\sound\hold.WAV"; break;
case "no":
strFileName=@"..\..\sound\no.WAV"; break;
case "popup":
strFileName=@"..\..\sound\popup.WAV"; break;
case "mayfall":
strFileName=@"..\..\sound\mayfall.WAV"; break;
}
//调用PlaySound方法,播放音乐
Helpers.PlaySound(strFileName, IntPtr.Zero, Helpers.PlaySoundFlags.SND_FILENAME | Helpers.PlaySoundFlags.SND_ASYNC); }
}
}
(三).使用