C#播放声音的四种方法C#播放声音的四种方法C#播放声音的四种方法介绍之前首先推荐一个程序员专用搜索引擎一http://www・ openso・ net 第一种是利用DirectX1.安装了DirectX SDK (有9个DLL文件)。
这里我们只用到Microsoft. DirectX, dll和Microsoft・ Directx・ DirectSound・ dll 2•引入DirectX的DLL文件的名字空间:using Microsoft. DirectX;using Microsoft. DirectX・ DirectSound;3.建立设备Device dv=new Device();4.设置CooperativeLevel o 因为windows 是多任务的系统,设备不是独占的SecondaryBufferbuf=new SecondaryBuffer(@"snd・ wav", dv);5.开辟缓冲区SecondaryBuffer buf=newSecondaryBuffer (@/z snd. wav", dv);6.接下来就可以播放啦。
第一个参数表示优先级别,0是最低的。
第2个参数是播放方式,这里是循环播放。
buf・ Play(0, BufferP1ayFlags・ Looping); 第二种是利用Microsoft speech objectLibrary/// <summaryIII播放声音文件III </summary〉III <param name二"FileName">文件全名</param>public void PlaySound(string FileName){//要加载COM 组件:Microsoft speech object Library(!System. I0・ File・ Exists(FileName))return;SpeechLib・ SpVoiceClass pp 二new SpeechLib・ SpVoiceClass();SpeechLib・ SpFileStreamClass spFs = new SpeechLib・SpFileStreamClass();spFs・ Open(FileName,SpeechLib・ SpeechStreamFileMode・ SSFMOpenFo rRead, true);SpeechLib・ISpeechBaseStream1stream = spFs as SpeechLib・ISpeechBaseStream;pp・ SpeakStream(lstream, SpeechLib・ SpeechVoiceSpeakFlags・ SVSFIsFil ename);spFs・ Close ();第三种:引用SoundPlayerSystem・ Media・ SoundPlayer sndPlayer = new System・ Media・ SoundPlayer(Application. Star tupPath+@/z/pm3. wav");sndPlayer・ PlayLooping ();第 4 种:利用Windows Media Player新建一个C#的Windows Form工程(Windows应用程序),并且定义两个菜单按钮(menu It eml, menult em2)。
选择菜单中的“工具”中的“自定义工具箱(添加/移除工具箱项)”,在自定义工具箱的窗口中, 点击展开“COM组件”项,选中“Window Media Player”选项。
确定后在“工具箱”中便会出现a Windows Media Player^ 这一项,然后再将其拖至Form上,调整大小,系统在“引用”中自动加入了对此dll的引用,AxMediaPlayer就是我们使用的Namespace与class。
在属性栏中设置好此控件的一些属性,为了方便,这里我把AutoStart设置成为true (其实默认是true),只要FileName被设置(打开了文件),则文件将会自动播放。
完整代码如下:private void menulteml_Click(object sender, System・ EventArgs e)OpenFileDialog ofDialog OpenFileDialog();new ofDialog. AddExtension 二true; ofDialog・CheckF订eExists = true; ofDialog・CheckP且thExists = true;//the next sentence must be in single line ofDialog. Filter = "VCD 文件(*. dat) | *. dat | Audio 文件(*. avi) | *. avi| WAV 文件(*・ wav) | *・ wav | MP3 文件(*・mp3)| *・mp31所有文件(*・*) I *・*";ofDialog・DefauItExt 二"*・mp3"; if(ofDialog・ShowDialog() DialogResult. OK)方法// 2003 一下版本t his. axMe d i aP 1 ay er 1 • FilofDialog・ FileName;this・ axMediaPlayer1・ URL二ofDialog. FileName: //2005 用法这里使用的是微软的播放器,大家也可以试试要显示,你只要把AxMediaPlayer的Visible属性设置为false就可以了。
// Sound・cs// (c)Copyright Jason Clark 2003/ / Shows a variety of basicmarshalling concepts by making soundsWinamp的控件,如果你只需要播放声音而不需using System;using Wintellect・Interop・ Sound;class App{public static void MainO {// Produce an OK beepSound. MessageBeep (BeepTypes. Ok);System. Threading. Thread. Sleep(1000);// 0k,now for some circa-1977si-fiRandom rand=newRandom ();for (Int32index二0; index< 7;index++ ){TimeSpan・ FromSeconds (・ 10));Sound< Beep ( rande Next (500)+1000,}// Pick a wave, any waveSound. PlayWave( @"C:\WINDOWS\Media\BATT LOW. WAV", true );System. Threading. Thread. Sleep( 2000 )Sound・ StopWave ();namespace Wintellect・Interop・ Sound{ usingSystem・ Runtime・InteropServices;using System. ComponentModel;sealed class Sound{//MessageBeep() wrapperpublic staticMessageBeep(BeepTypes type)if ( !MessageBeep( type )){Int32Marshal. GetLastWin32Error ();t hrowWin32Exception(err );} } // Friendlybeep wrapperpublic staticBeep (Int32 frequency, milliseconds) {if(!UnmanagedBeep( (Ulnt32)frequency,(UInt32)milli seconds )){Friendlyvoid (UInt32)err =newlow-levelvoid Int32Int32 err = Marshal. GetLastWin32Error();throw new Win32Exception( err );}}// Friendly low-level beep wrapper with TimeSpanpublic static voidBeep (Int32 frequency, TimeSpan duration) {Beep( frequency, (Int32)duration. TotalMilliseconds );}// Friendly PlaySound() wrapper for playing wave filespublic static voidPlayWave(String filename, Boolean looped) {UInt32 flags 二sndAsyncFlag| sndFilenameFlag;if ( looped ) flags |= sndLoopFlag;if( !PlaySound( filename,IntPtr. Zero, flags ) ) {Int32 err = Marshal. GetLastWin32Error();throw new Win32Exception( err );}}// Friendly PlaySound() wrapper for playing wave filespublic static voidPlayWave(String filename){PlayWave( fi1ename, false );// Friendly PlaySound() wrapperfor stopping wave publicstaticfilesvoid StopWave () {PlayWave( }null );// static externmethodsfor making sound throughinterop[DllImport ( "User32・ dll",Set Las tError二t rue )]static extern BooleanMessageBeep(UInt32beepType);"Kernel32. dll',"Beep", Set Las tEirorstaticUnmanagedBeep (Ulnt32 UInt32 duration);[Dlllmport( EntryPoint = true)]extern Booleanfrequency,[Dlllmport ("Winmm. dll",CharSet ・ Auto,privateSound () {}P1aySound(String filename, UInt32 flags);IntPtrmodule,//Some private helper valuesforcallingPlaySoundconstUInt32sndAsyncFlag=0x0001;constUInt32sndLoopFlag=0x0008;constUInt32sndFi1enameF1ag二0x00020000;staticexternBoolean CharSet SetLastErrortrue)]// Enum for message beep t ypesenum BeepTypes{Simple = ~1,Ok二0x00000000,IconHand= 0x00000010,IconQuestion = 0x00000020,IconExclamation 二0x00000030,IconAsterisk = 0x00000040}[DlllmportC'Winmm.dH")]public static extern long PlaySound(string namejong module, long[DlllmportCwinmm.dir')] extern long mciSendString(string lpstrCommand z stringng lengthjong hwndcallback); private string m_MusicName=""; private void PlayMusic() <m_MusicName="\M,,+Tool.ReadInfoCpromptmusicfile',)+',\"M ; if(m_MusicName.Length==O) return; try {mciSendString(@M close M + m^MusicName/* ”,0,0);mciSendString(@t 'open " + m_MusicName z ""AO);mciSendStringC^'play w + m^MusicName /”,0,0); } catch {}private void StopMusic() { try {mciSendString(@M close " + m_Mu5icN3me 「W); } catch{}flag);IpstrReturnStringJoprivate static播放内存中的WAV文件可以这样://API定义private const int SND_ASYNC = 0x1;private const int SND_MEMORY = 0x4;[DllImport(N winmm.dir)]private static extern int sndPlaySoundA(byte[] IpszSoundName, int uFlags);〃将blipl.wav添加入工程并设置为嵌入的资源〃现在是将它读入内存备用Type t=this.GetType();System.Reflection.Assembly a=t. Assembly;System.IO.Stream stream=a.GetManifestResourceStream(space+".blipl.wav M); byte[] ba=new byte[stream.Length];stream.Read(ba,O, ba.Length);stream.Close();〃播放缓存sndPlaySoundA(ba z SND_MEMORY);• 用API函数winmm下的PlaySound播放声音:(-).说明一个播放音乐的类Z要准备好自己的音乐文件,比如:*.mid/*.wav等(二)•步骤using System;using System.Collections;using ponentModel;using System.Runtime.InteropServices;namespace欽棋游戏音效支持类{III <summary>III用于播放音乐III </summary>internal class Helpers{[Flags]public enum PlaySoundFlags : int{SND_SYNC = 0x0000, /* play synchronously (default) */ 〃同步SND_ASYNC = 0x0001z/* play asynchronously */ 〃异步SND_NODEFAULT = 0x0002, /* silence (idefault) ifsound 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 */}[DIIImport(N winmm N)]public static extern bool PlaySound( string szSound, IntPtr hMod f PlaySoundFlags f lags);}public class Sound{public static void Play( string strFileName ){switch(strFileName)case "start": strFileName=@"..\..\sound\start.WAV M; break;case M back M: strFileName=@"..\..\sound\back.WAV"; break;case "fall”: strFileName=@"..\..\sound\fall.WAV"; break;case w huiqi": strFileN3me=@"・・\・・\soimd\huiqi・WA\T; b reak;case w huiqiend w: strFileName=@"..\..\sound\huiqiend.WAV M; break;case w jiangjun M: strFileName=@M..\-\sound\jiangjun.WAV w; break;case w kiir: strFileName=@M..\..\sound\kill.WAV w; break;case W win": strFileName=@',..\..\sound\win.WAV w; break;case w move M: strFileName=@'\.\-\sound\move.WAV"; break;case ”hold": strFileName=@"..\..\sound\hold.WAV M; break;case w no M: strFileName=@',..\..\sound\no.WAV w; break;case "popup": strFileName=@M..\..\sound\popup.WAV*'; break;case M mayfair,: strFileName=@"..\..\sound\mayfall.WAV M; break;〃调用PlaySound方法,播放音乐Helpers.PlaySound(strFileName, IntPtr.Zero f Helpers.PlaySoundFlags.SND_FILEN AME |Helpers.PlaySoundFlags.SND_ASYNC); }}}(三)使用1 •潘加组件(Interop.WMPLib)・这个类库自带的,默认没有淞加进来.方法:展开项目文件死右击引用,添加引用,到Com组件栏z找到添加到项目中.2 •新建一个匸cs文件,把这些代码拷贝进去,全部覆盖即可,并修改上例子中的播放文件名.就是这样的语句:strFileName=@M..\..\sound\mayfall.WAV,; 〃一定嬰存在这个音乐文件,否则不能播放3 •如果调用这个方法的地方与此类不在同一个命名空间•要左用的地方打开类的命名空间.方法:如这个示例类的命名空间应该这样功using PlaySound;最后就可以用了,用法极简单,直接调用此类的方法:Soiind.Play(M move-); 〃其中参数为音乐文件名(自定义)相应Blog链接:/chengking/archive/2005/10/07/496627.aspx using System;using System. Collections. Generic;using System・Linq;using System. Text;using System. Runtime. InteropServices;namespace MovSysSht{internal class CSoundPlay{public CSoundPlay(){//// TODO:在此处添加构造函数逻辑//}[Flags]public enum PlaySoundFlags : int {SND_SYNC = 0x0000, /* play synchronously (default) */SND_ASYNC = 0x0001, /* play asynchronously */SNDJODEFAULT = 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 */SNDJIOWAIT = 0x00002000, /* don't wait if the driver is busy */SND^LIAS = 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 ertom */}[Dlllmport("winmm・ dll")]public static extern bool PlaySound(string szSound, IntPtr hMod, PlaySoundFlags flags);}public class Sound{public static void Play(string strFileName){CSoundPlay. PlaySound(strFileName, IntPtr. Zero, CSoundPlay. PlaySoundFlags. SND_FILENAME | CSoundPlay. PlaySoundFlags. SND_ASYNC);}C#播放mp3控件C#播放器空件的常用方法MediaPlay 9右击工具箱・>选择项⑴…・> 显示■选择工具箱项-・> COM组件・> Windows Media Playe r wmp.dll 添加axWindowsMediaPlayerl.windowlessVideo = false; 〃设为false 后双击屏蔓可以全屏axWindowsMediaPlayerl.fullScreen = true; 〃设播放器全屏播放axWin d o wsM ed la Play er 1 .URL = @ "mmsy/192.168.0.102/vod/jing wei.wmaaxWindowsMediaPlayerl.Ctlcontrols.playO;〃扌番放axWindowsMediaPlayerl.Ctlcontrols.stopO; 〃停止axWindowsMediaPlayerl.Ctlcontrols.pauseQ;〃暂停axWindowsMediaPlayerl.settings^utoStart = true; 〃自动播放axWindowsMediaPlayerl.settings.mute = false;〃静音axWindowsMediaPlayerl.settings.volume = 100; // 音星int 0 ~ 100 100 是最大音星axWindowsMediaPlayerl.currentMedia.duration.ToStringO;// 影片长度axWindowsMediaPlayerl.Ctlcontrols.currentPosition = 30; 〃当前的播放位置doubleaxWindowsMediaPlayerl.currentMedia.getItemInfo("Title");//^ 题axWindowsMediaPlayerl.currentMedia.getltemlnfoC^uthor");//^^//*////*// MediaPlay以前版本右击工具箱・>选择项⑴…•>显示•选择工具箱项•COM组件•>浏览(B)…・>CzWINDO WS\system32\msdxm.ocx ・>打开Windows Media Player msdxm.dll 添加-a b e H H e x t HaxMediap-ayerl ・v2ume ・T0stz.ng();、、IDft waxMediapETyerl.FimName n ◎-mmsz/、218・98・lol・164、vod0ingw2.・vvmaJ、、>444^HSaxMed 貳pEryerl.p亦y();、、w st諦第S H 3-v i ®«s .: .V .V n o s 1 -V Rea_pEryer-G2Coritro一rmoc3260・d=saxRe 竺Audiol ・sourceN◎T,mp3\hh ・mp3「、、諦男常raaxRe 竺Audiol.can 卫aypauseo" 、、BOO-axRea-Audiol.canpauseo"、、IK ^axRe 竺Audiol・axRea-Audiol.canmayo」axRea -Audio1 ・Do、、BOO-砌)課諦并、、巔saxR 蛊一Audiol ・seKenter(t2e); 、、菇網工洞H m B shitp Er c e HaxRea-Audiop.GetposaonojaxRea-Audiol.DOSrfropojaxRea 一Audio l.s etcenteA**<«%、、苗®诵労axRea>udiol ・setcenter(true)jw^axRea -Audio1 ・Do卫ay()jaxRea-Audiol ・setposson(p5rce)一nResL HaxRea-Audiol.GetposEono-'/^oilDllHmj决工s m男毎冊wbe-l.Text"殳Re 竺Audiol.GetTitmo;、询4®終耳53rl弼Er b e一2・TextH•!!}:曽§哥那一 -+axRea-Audiol.GetBandwidthcurreng、一024+・K B J、、11H習緞 AS11H習3那挪貳 beH.TextH•侨苗§哥8|}: - +axRea_Audo-l・Ge(conn<t>20nBn>ndwickho、一024 + ・KBJ、、11H習3廨游3序跚怎么获取mp3的头文件信息比如歌曲名,歌手等呵呵.我以前回答过这个问题,可以看看以前我的得分贴:!/Expert/topic/2349/2349762.xml?temp=.1675074static void Main(string[] args){byte[] b = new byte[128];string sTitle;string sSinger;string sAlbum;string sYear;string sComm;Filestream fs = new FileStream(@M d:\mp3.mp3", FileMode.Open);fs.Seek(-128z SeekOrigin.End);fs.Read(b, 0, 128);bool isSet=false;String sFlag = System.Text.Encoding.Default.GetString(b/ 0, 3); if (pareTo(M TAG,,)==0){System.Console.WriteLine ("Tag is setted!"*);isSet=tme;}if (isSet){//get title of song;sTitle = System.Text.Encoding.Default.GetString (b.3,30);System.Console.WriteLine ("Title:" + sTitle);//get singer;sSinger = System.Text.Encoding.Default.GetString (b z33r30);System.Console.WriteLine ("Singer:'* + sSinger);//get album;sAlbum = System.Text.Encoding.Default.GetString (b z63z30);System.Console.WriteLine ("Album:" + sAlbum);//get Year of publish;sYear= System.Text.Encoding.Defau It.GetString (b z93f4);System.Console.WriteLine (M Year:w + sYear);//get Comment;sComm= System.Text.Encoding.Default.GetString (1),97,30);System.Console.WriteLine (^Comment:*' + sComm);}System.Console.WriteLine(n Any keyto exit!*'); System.Console.Read();}上面是取得Vl的方法C#中用API实现MP3等音频文件的播放类C#s有提供播放MP3等音频文件的类.要編写播放MP3等音频文件程席,必须使用第三方控件或类。