四種利用C#播放聲音的方法
本文將介紹利用C#播放聲音的四種方法,希望那個通過本文,大家能在C#播放聲音方面有所突破。本文使用的是微軟的播放器,其他播放器大家可以嘗試。
第一種是利用DirectX
1.安裝了DirectX SDK(有9個DLL文件)。這里我們只用到MicroSoft.DirectX.dll 和 Microsoft.Directx.DirectSound.dll
2.引入DirectX 的DLL文件的名字空間:
- using Microsoft.DirectX;
- using Microsoft.DirectX.DirectSound;
3.建立設(shè)備
Device dv=new Device();
4.設(shè)置CooperativeLevel。因為windows是多任務(wù)的系統(tǒng),設(shè)備不是獨占的
SecondaryBuffer buf=new SecondaryBuffer(@"snd.wav",dv);
5.開辟緩沖區(qū)SecondaryBuffer buf=new SecondaryBuffer(@"snd.wav",dv);
6.接下來就可以播放啦。第一個參數(shù)表示優(yōu)先級別,0是最低的。第2個參數(shù)是播放方式,這里是循環(huán)播放。
buf.Play(0,BufferPlayFlags.Looping);
第二種是利用Microsoft speech object Library
- ///
- /// 播放聲音文件
- ///
- /// 文件全名
- public void PlaySound(string FileName)
- {//要加載COM組件:Microsoft speech object Library
- if (!System.IO.File.Exists(FileName))
- {
- return;
- }
- SpeechLib.SpVoiceClass pp = new SpeechLib.SpVoiceClass();
- SpeechLib.SpFileStreamClass spFs = new SpeechLib.SpFileStreamClass();
- spFs.Open(FileName, SpeechLib.SpeechStreamFileMode.SSFMOpenForRead, true);
- SpeechLib.ISpeechBaseStream Istream = spFs as SpeechLib.ISpeechBaseStream;
- pp.SpeakStream(Istream, SpeechLib.SpeechVoiceSpeakFlags.SVSFIsFilename);
- spFs.Close();
- }
第三種:引用SoundPlayer
- System.Media.SoundPlayer sndPlayer = new System.Media.SoundPlayer(Application.StartupPath+@"/pm3.wav");
- sndPlayer.PlayLooping();
第4種:利用Windows Media Player
新建一個C#的Windows Form工程(Windows應(yīng)用程序),并且定義兩個菜單按鈕(menuItem1,menuItem2)。
選擇菜單中的“工具”中的“自定義工具箱(添加/移除工具箱項)”,在自定義工具箱的窗口中,點擊展開“COM 組件”項,選中“Window Media Player”選項。確定后在“工具箱”中便會出現(xiàn)“Windows Media Player”這一項,然后再將其拖至Form上,調(diào)整大小,系統(tǒng)在“引用”中自動加入了對此dll的引用,AxMediaPlayer就是我們使用的Namespace與class。
在屬性欄中設(shè)置好此控件的一些屬性,為了方便,這里我把AutoStart設(shè)置成為true(其實默認是true),只要FileName被設(shè)置(打開了文件),則文件將會自動播放。完整代碼如下:
- private void menuItem1_Click(object sender, System.EventArgs e)
- {
- OpenFileDialog ofDialog = new OpenFileDialog();
- ofDialog.AddExtension = true;
- ofDialog.CheckFileExists = true;
- ofDialog.CheckPathExists = true;
- //the next sentence must be in single line
- 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屬性設(shè)置為false就可以了。
【編輯推薦】