C#播放背景音乐的方法小结
本文实例总结了C#播放背景音乐的方法。分享给大家供大家参考。具体分析如下:
最经在写winform程序,其中有用到播放背景音乐
特此收集了一些网上的教程:
1、调用非托管的dll
usingSystem.Runtime.InteropServices; //DllImport命名空间的引用 classtest//提示音 { [DllImport("winmm.dll")] publicstaticexternboolPlaySound(StringFilename,intMod,intFlags); publicvoidMain() { PlaySound(@"d:/qm.wav",0,1); //把1替换成9,可连续播放 } }
2、播放系统自带声音
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.SoundPlayersp=newSoundPlayer(); sp.SoundLocation=@"D:\10sec.wav"; sp.PlayLooping();
4、使用MCICommandString多媒体设备程序接口播放mp3,avi等
usingSystem.Runtime.InteropServices; publicstaticuintSND_ASYNC=0x0001; publicstaticuintSND_FILENAME=0x00020000; [DllImport("winmm.dll")] publicstaticexternuintmciSendString(stringlpstrCommand, stringlpstrReturnString,uintuReturnLength,uinthWndCallback); publicvoidPlay() { mciSendString(@"closetemp_alias",null,0,0); mciSendString(@"open""E:\Music\青花瓷.mp3""aliastemp_alias",null,0,0); mciSendString("playtemp_aliasrepeat",null,0,0); }
关于mciSendString的详细参数说明,请参见MSDN,或是http://blog.csdn.net/psongchao/archive/2007/01/19/1487788.aspx
5、使用axWindowsMediaPlayer的COM组件来播放
a.加载COM组件:ToolBox->ChooseItems->COMComponents->WindowsMediaPlayer:
b.把WindowsMediaPlayer控件拖放到Winform窗体中,把axWindowsMediaPlayer1中URL属性设置为MP3或是AVI的文件路径,F5运行。
如何使用WindowsMediaPlayer循环播放列表中的媒体文件?
假设我们有一个播放列表,下面的代码可以实现自动循环播放
privatevoidaxWindowsMediaPlayer1_PlayStateChange(objectsender,AxWMPLib._WMPOCXEvents_PlayStateChangeEvente) { if(axWindowsMediaPlayer1.playState==WMPLib.WMPPlayState.wmppsMediaEnded) { Threadthread=newThread(newThreadStart(PlayThread)); thread.Start(); } } privatevoidPlayThread() { axWindowsMediaPlayer1.URL=@"E:\Music\SomeOne.avi"; axWindowsMediaPlayer1.Ctlcontrols.play(); }
希望本文所述对大家的C#程序设计有所帮助。