C#播放聲音的四種方法


 介紹之前首先推薦一個程序員專用搜索引擎-http://www.openso.net

第一種是利用DirectX
1.安裝了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。因為windows是多任務的系統,設備不是獨占的
SecondaryBuffer buf=new SecondaryBuffer(@"snd.wav",dv);
5.開辟緩沖區SecondaryBuffer buf=new SecondaryBuffer(@"snd.wav",dv);

6.接下來就可以播放啦。第一個參數表示優先級別,0是最低的。第2個參數是播放方式,這里是循環播放。
 buf.Play(0,BufferPlayFlags.Looping);
第二種是利用Microsoft speech object Library

/// <summary

        /// 播放聲音文件

        /// </summary>

        /// <param name="FileName">文件全名</param>

        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應用程序),並且定義兩個菜單按鈕(menuItem1,menuItem2)。
  選擇菜單中的“工具”中的“自定義工具箱(添加/移除工具箱項)”,在自定義工具箱的窗口中,點擊展開“COM 組件”項,選中“Window Media Player”選項。確定后在“工具箱”中便會出現“Windows Media Player”這一項,然后再將其拖至Form上,調整大小,系統在“引用”中自動加入了對此dll的引用,AxMediaPlayer就是我們使用的Namespace與class。
  在屬性欄中設置好此控件的一些屬性,為了方便,這里我把AutoStart設置成為true(其實默認是true),只要FileName被設置(打開了文件),則文件將會自動播放。完整代碼如下:

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屬性設置為false就可以了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM