C#中播放背景音樂幾種的方法
最經(jīng)在寫winform程序,其中有用到播放背景音樂
特此收集了一些網(wǎng)上的教程:
1邀摆、調(diào)用非托管的dll
? ? ? ?using System.Runtime.InteropServices; ?//DllImport命名空間的引用
class test ?//提示音
{
[DllImport("winmm.dll")]
public static extern bool PlaySound(String Filename,int Mod,int Flags);
public void Main()
{
PlaySound(@"d:/qm.wav",0,1); ? //把1替換成9笑诅,可連續(xù)播放
}
? ? ? ?}
2、播放系統(tǒng)自帶聲音
? ?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();
3挟炬、使用System.Media.SoundPlayer播放wav
System.Media.SoundPlayer sp = new SoundPlayer();
sp.SoundLocation = @"D:\10sec.wav";
sp.PlayLooping();
4焰络、使用MCI Command String多媒體設(shè)備程序接口播放mp3,avi等
using System.Runtime.InteropServices;
public static uint SND_ASYNC = 0x0001;
public static uint SND_FILENAME = 0x00020000;
[DllImport("winmm.dll")]
public static extern uint mciSendString(string lpstrCommand,
string lpstrReturnString, uint uReturnLength, uint hWndCallback);
public void Play()
{
mciSendString(@"close temp_alias", null, 0, 0);
mciSendString(@"open ""E:\Music\青花瓷.mp3"" alias temp_alias", null, 0, 0);
mciSendString("play temp_alias repeat", null, 0, 0);
}
關(guān)于mciSendString的詳細參數(shù)說明符喝,請參見MSDN闪彼,或是 http://blog.csdn.net/psongchao/archive/2007/01/19/1487788.aspx
5、使用axWindowsMediaPlayer的COM組件來播放
a.加載COM組件:ToolBox->Choose Items->COM Components->Windows Media Player如下圖:
b.把Windows Media Player控件拖放到Winform窗體中协饲,把axWindowsMediaPlayer1中URL屬性設(shè)置為MP3或是AVI的文件路徑畏腕,F(xiàn)5運行。
如何使用Windows Media Player循環(huán)播放列表中的媒體文件茉稠?
假設(shè)我們有一個播放列表描馅,下面的代碼可以實現(xiàn)自動循環(huán)播放
private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if (axWindowsMediaPlayer1.playState == WMPLib.WMPPlayState.wmppsMediaEnded)
{
Thread thread = new Thread(new ThreadStart(PlayThread));
thread.Start();
}
}
private void PlayThread()
{
axWindowsMediaPlayer1.URL = @"E:\Music\SomeOne.avi";
axWindowsMediaPlayer1.Ctlcontrols.play();
}
?