{範例} WPF在Windows XP上播放音效

要在WPF中播放音效,透過 Multimedia 相關的API可以很容易完成
(可參閱: http://msdn.microsoft.com/en-us/library/aa970915.aspx )。

但若需要在Windows XP上執行,需要注意幾件事:

1. WPF 中 MediaElement and MediaPlayer 這兩類別執行時,須要安裝 Microsoft Windows Media Player 10 以上版本。當執行的 Windows XP 搭配是Media Player 9 時,程式沒有作用,不會發出聲音 (還好,程式也不會當掉)。

2. Windows Media Player 預設可以播放的聲音格式不多,可以參閱微軟KB說明。若想要播放不支援的檔案(如 *.ogg 的格式),可以另外尋找該檔案的Codec。( *.ogg 的 Codec 可以到這裡下載 )

若是 Windows XP 可以將 Media Player 升級至 10 以上版本,那應該比較沒問題。

筆者遇到的情況是:

WPF 應用程式希望可以在 Windows XP + Media Player 9 執行。

以WPF 預設的 Multimedia 是無法達成的,所以解決方法如下 :

1. 實作一個 Windows UserControl, 加入 WindowsMedia Player 的 COM 元件,做為播放聲音的處理,可以參考這篇說明,文中重點就是從 VS2010 的 [工具箱] 加入項目。

1

 

2. 將上述的UserControl Host 在 WPF 中,MSDN有實作說明,摘要 Host 作法如下:

    // Create the interop host control.
System.Windows.Forms.Integration.WindowsFormsHost host =
new System.Windows.Forms.Integration.WindowsFormsHost();

// Create the MaskedTextBox control.
Mycontrol ctrl= new Mycontrol ();

// Assign the control as the host control's child.
host.Child = ctrl;


如此一來,WPF 可以不必局限 Media Player 10 以上的限制了。



實作的結果沒幾行程式,過程卻也費了不工夫,有興趣者可以下載