C#中播放背景音乐几种的方法

来源:互联网 发布:c语言 long int 编辑:程序博客网 时间:2024/05/22 03:52
最经在写winform程序,其中有用到播放背景音乐

特此收集了一些网上的教程:

1、调用非托管的dll

[csharp] view plain copy
  1.        using System.Runtime.InteropServices;  //DllImport命名空间的引用     
  2. class test  //提示音  
  3. {  
  4.     [DllImport("winmm.dll")]  
  5.     public static extern bool PlaySound(String Filename,int Mod,int Flags);  
  6.   
  7.     public void Main()  
  8.     {  
  9.         PlaySound(@"d:/qm.wav",0,1);   //把1替换成9,可连续播放  
  10.     }  
  11.        }  

2、播放系统自带声音


[csharp] view plain copy
  1.   System.Media.SystemSounds.Asterisk.Play();   
  2. System.Media.SystemSounds.Beep.Play();   
  3. System.Media.SystemSounds.Exclamation.Play();   
  4. System.Media.SystemSounds.Hand.Play();   
  5. System.Media.SystemSounds.Question.Play();  

3、使用System.Media.SoundPlayer播放wav

[csharp] view plain copy
  1. System.Media.SoundPlayer sp = new SoundPlayer();   
  2.   sp.SoundLocation = @"D:\10sec.wav";   
  3.   sp.PlayLooping();  

4、使用MCI Command String多媒体设备程序接口播放mp3,avi等

[csharp] view plain copy
  1. using System.Runtime.InteropServices;   
  2.   public static uint SND_ASYNC = 0x0001;   
  3.   public static uint SND_FILENAME = 0x00020000;   
  4.   [DllImport("winmm.dll")]   
  5.   public static extern uint mciSendString(string lpstrCommand,   
  6.   string lpstrReturnString, uint uReturnLength, uint hWndCallback);   
  7.   public void Play()   
  8.   {   
  9.   mciSendString(@"close temp_alias"null, 0, 0);   
  10.   mciSendString(@"open ""E:\Music\青花瓷.mp3"" alias temp_alias"null, 0, 0);   
  11.   mciSendString("play temp_alias repeat"null, 0, 0);   
  12.   }  
关于mciSendString的详细参数说明,请参见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属性设置为MP3或是AVI的文件路径,F5运行。

  如何使用Windows Media Player循环播放列表中的媒体文件?

  假设我们有一个播放列表,下面的代码可以实现自动循环播放

[csharp] view plain copy
  1. private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)   
  2.   {   
  3.   if (axWindowsMediaPlayer1.playState == WMPLib.WMPPlayState.wmppsMediaEnded)   
  4.   {   
  5.   Thread thread = new Thread(new ThreadStart(PlayThread));   
  6.   thread.Start();   
  7.   }   
  8.   }   
  9.   private void PlayThread()   
  10.   {   
  11.   axWindowsMediaPlayer1.URL = @"E:\Music\SomeOne.avi";   
  12.   axWindowsMediaPlayer1.Ctlcontrols.play();   
  13.   } 
原创粉丝点击