文章分類

2013年7月22日 星期一

[WPF] 音樂和音效之播放

[ 音樂 ]
一般都直接"手動"將聲音檔放到debug/bin裡面。

1. 音效

因為音效通常都為短暫急促的(也不會同時播一個以上的音效),
故可利用SoundPlayer Computer.Aduio載入記憶體來播放,
缺點就是一次只能播一個,當你想播放A時,又播B,A就會被覆蓋掉。

方法(1) - SoundPlayer

using System.Media;   //引入SoundPlayer所在的Media命名空間

SoundPlayer _sp = new SoundPlayer();    //實作出來SoundPlayer
_sp.SoundLocation = "mosquito.wav";     //設定聲音檔來源,只能wav副檔名_sp.Load();                     //載入記憶體
_sp.Play();                      //播一次
_sp.PlayLooping();         //循環播放
_sp.Stop();                     //停止播放

方法(2) - Computer.Aduio

//using前先加入VB"參考"
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.Devices;

Computer myComputer = new Computer();

//循環播放
myComputer.Audio.Play("mosquito.wav",AudioPlayMode.BackgroundLoop);

//直到播放完 才繼續程式
//myComputer.Audio.Play("mosquito.wav",AudioPlayMode.WaitToComplete);

//停止播放
myComputer.Audio.Stop();            

-----------------------------------------------------------------------------------------------------------------------------

2. 音樂

然而音樂通常都要一直播(不能被中斷),所以不能用剛剛的方法,
只好改用WindForm中的Media Player控制項

Step1.工具箱=>滑鼠右鍵=>選擇項目
Step2.切換至『COM 元件』頁籤=>勾選Windows Media Player=>確定
Step3.會發現工具箱多了個Windows Media Player的控制項
Step4.加入Windows Media Player控制項到設計表單,可看到如下的畫面。

//設定不自動撥放
this.axWindowsMediaPlayer1.settings.autoStart = false;                     
//設定音量調整Bar最小值為最小音量值(0)
this.tbarVolume.Minimum = 0;
//設定音量調整Bar最大值為最大音量值(100) 
this.tbarVolume.Maximum = 100;
//設定音量調整Bar目前值為目前音量值 
this.tbarVolume.Value = this.axWindowsMediaPlayer1.settings.volume;        
this.timer1.Enabled = true;
 
//開啟檔案 
this.axWindowsMediaPlayer1.URL = "background_music.wav";

//播放
this.axWindowsMediaPlayer1.Ctlcontrols.play(); 

//停止播放
this.axWindowsMediaPlayer1.Ctlcontrols.stop();         

//暫停撥放
this.axWindowsMediaPlayer1.Ctlcontrols.pause(); 

//改變音量大小 
this.axWindowsMediaPlayer1.settings.volume = this.tbarVolume.Value;
 
 

沒有留言:

張貼留言