C#播放聲音【六種方法】

C#中聲音的播放主要有六種方法:
1.播放系統事件聲音 
2.使用SoundPlayer
3.使用API函數播放
4.使用axWindowsMediaPlayer的COM組件來播放
5.Microsoft speech object Library

6.使用directX


1.播放系統事件聲音 

System.Media.SystemSounds.Asterisk.Play(); 
System.Media.SystemSounds.Beep.Play(); 
System.Media.SystemSounds.Exclamation.Play(); 
System.Media.SystemSounds.Hand.Play(); 
System.Media.SystemSounds.Question.Play();


2.使用SoundPlayer
SoundPlayer player = new SoundPlayer();
player.SoundLocation = @"D:\test.wav";
player.Load(); //同步加載聲音
player.Play(); //啓用新線程播放
//player.PlayLooping(); //循環播放模式
//player.PlaySync(); //UI線程同步播放


3.使用API函數播放

using System.Runtime.InteropServices;

public static class WavPlayer
{
    [DllImport("winmm.dll", SetLastError = true)]
    static extern bool PlaySound(string pszSound, UIntPtr hmod, uint fdwSound);
    [DllImport("winmm.dll", SetLastError = true)]
    static extern long mciSendString(string strCommand, 
        StringBuilder strReturn,int iReturnLength, IntPtr hwndCallback);
    [DllImport("winmm.dll")]
    private static extern long sndPlaySound(string lpszSoundName, long uFlags);

    [Flags]
    public enum SoundFlags
    {
        /// <summary>play synchronously (default)</summary>
        SND_SYNC = 0x0000,
        /// <summary>play asynchronously</summary>
        SND_ASYNC = 0x0001,
        /// <summary>silence (!default) if sound not found</summary>
        SND_NODEFAULT = 0x0002,
        /// <summary>pszSound points to a memory file</summary>
        SND_MEMORY = 0x0004,
        /// <summary>loop the sound until next sndPlaySound</summary>
        SND_LOOP = 0x0008,
        /// <summary>don’t stop any currently playing sound</summary>
        SND_NOSTOP = 0x0010,
        /// <summary>Stop Playing Wave</summary>
        SND_PURGE = 0x40,
        /// <summary>don’t wait if the driver is busy</summary>
        SND_NOWAIT = 0x00002000,
        /// <summary>name is a registry alias</summary>
        SND_ALIAS = 0x00010000,
        /// <summary>alias is a predefined id</summary>
        SND_ALIAS_ID = 0x00110000,
        /// <summary>name is file name</summary>
        SND_FILENAME = 0x00020000,
        /// <summary>name is resource name or atom</summary>
        SND_RESOURCE = 0x00040004
    }

    public static void Play(string strFileName)
    {
        PlaySound(strFileName, UIntPtr.Zero, 
           (uint)(SoundFlags.SND_FILENAME | SoundFlags.SND_SYNC | SoundFlags.SND_NOSTOP));
    }
    public static void mciPlay(string strFileName)
    {
        string playCommand = "open " + strFileName + " type WAVEAudio alias MyWav";
        mciSendString(playCommand, null, 0, IntPtr.Zero);
        mciSendString("play MyWav", null, 0, IntPtr.Zero);

    }
    public static void sndPlay(string strFileName)
    {
        sndPlaySound(strFileName, (long)SoundFlags.SND_SYNC);
    }
}
關於mciSendString的詳細參數說明,請參見MSDN,或是http://blog.csdn.net/psongchao/archive/2007/01/19/1487788.aspx


4.使用axWindowsMediaPlayer的COM組件來播放


選擇菜單中的“工具”中的“自定義工具箱(添加/移除工具箱項)”,在自定義工具箱的窗口中,點擊展開“COM 組件”項,選中“WindowMedia Player”選項。確定後在“工具箱”中便會出現“Windows Media Player”這一項,然後再將其拖至Form上,調整大小,系統在“引用”中自動加入了對此dll的引用,AxMediaPlayer就是我們使用的 Namespace與class。

把Windows Media Player控件拖放到Winform窗體中,把axWindowsMediaPlayer1中URL屬性設置爲MP3或是AVI的文件路徑。

private voidmenuItem1_Click(object sender, System.EventArgs e)
{
OpenFileDialogofDialog = new OpenFileDialog();
ofDialog.AddExtension= true;
ofDialog.CheckFileExists= true;
ofDialog.CheckPathExists= true;
//the nextsentence 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用法
}
}

5.Microsoft speech object Library

///<summary
/// 播放聲音文件
/// </summary>
/// <paramname="FileName">文件全名</param>
public voidPlaySound(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();
}


6. 使用directX

準備工作:

  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;

  2.建立設備。在我們導入的Microsoft.DirectX.DirectSound空間中,有個Device的類。這個是表示系統中的聲音設備。

Device dv=new Device();

  3.設置CooperativeLevel。因爲windows是多任務的系統,設備不是獨佔的,所以在使用設備前要爲這個設備設置CooperativeLevel。調用Device的SetCooperativeLevel方法:其中,第一個參數是一個Control,第二個參數是個枚舉類型。

  在這個程序中,Control我隨便弄了個參數塞進去(很汗吧!)。如果在windows程序中,可以用this代替。第二個參數就是優先級別,這裏表示優先播放。 

dv.SetCooperativeLevel((new UF()),CooperativeLevel.Priority);

  4.開闢緩衝區。對於上面的聲音設備,他有個自己的緩衝區,叫主緩衝區。系統中,一個設備有唯一的主緩衝區。由於windows是多任務(又是這個!),所以可以有幾個程序同時利用一個設備播放聲音,所以每個程序都自己開闢一個二級緩衝區,放自己的聲音。

  系統根據各個程序的優先級別,按照相應的順序分別去各個二級緩衝區中讀取內容到主緩衝區中播放。這裏,我們爲SND.W***開闢一個緩衝區。

  其中,第一個參數表示文件名(傻瓜都看出來了!),第二個就是需要使用的設備。

SecondaryBuffer buf=new SecondaryBuffer(@"snd.wav",dv);

  5.接下來就可以播放啦。第一個參數表示優先級別,0是最低的。第2個參數是播放方式,這裏是循環播放。

buf.Play(0,BufferPlayFlags.Looping);

  6.由於命令行程序沒有消息循環,執行完代碼就退出了,所以,我們需要暫停程序。

Console.Read();

  7.關鍵的部分已經完了,這裏只是交代一下剛纔的那個倒黴的new UF() 是什麼東西。這個完全是爲了應付SetCooperativeLevel的參數要求。我不知道這樣做有什麼附作用(各位如果因此把聲卡燒了…………)

class UF:Form{}

  8.代碼寫完啦~~~。下面可以編譯了,這裏編譯比較複雜點。

csc /r:directX/MicroSoft.DirectX.dll;directX/Microsoft.Directx.DirectSound.dll dxsnd.cs

  這裏,我把2個DLL文件放在當前目錄的directx目錄下(這個是我自己建的,你只需要指出這2個文件的位置就可以了。)

  順便把我的目錄結構說明一下:

|
|--dxsnd.cs
|--snd.wav
|--<directx>
|
|--MicroSoft.DirectX.dll
|--Microsoft.Directx.dll

  下面是完整代碼:

//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{}
 }
}


參考:http://blog.csdn.net/holyrong/article/details/1748500

    http://www.cnblogs.com/net-study/archive/2013/07/10/3181674.html

    http://www.sufeinet.com/thread-459-1-1.html

發佈了81 篇原創文章 · 獲贊 104 · 訪問量 131萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章