四联光电智能照明论坛

标题: C#播放音频文件的四种方式 [打印本页]

作者: admin    时间: 2016-11-16 22:33
标题: C#播放音频文件的四种方式



1.播放系统事件声音
2.使用System.Media.SoundPlayer播放
wav
3.使用MCI Command String多媒体设备程序接口播放mp3avi

4.使用axWindowsMediaPlayerCOM组件来播放

具体的使用方法:

1.播放系统事件声音
  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();

2.使用System.Media.SoundPlayer播放wav

using System.Media;

System.Media.SoundPlayersp = new SoundPlayer();

sp.SoundLocation= @"F:\\恋爱ing.wav";      //音频文件路径

sp.PlayLooping();

3.使用MCICommand String多媒体设备程序接口播放mp3avi
  using System.Runtime.InteropServices;
  
public static uint SND_ASYNC = 0x0001;
  
public static uint SND_FILENAME =0x00020000;
  
[DllImport("winmm.dll")]
  
public static extern uintmciSendString(string lpstrCommand,
  
string lpstrReturnString, uintuReturnLength, uint hWndCallback);
  
public void Play()
  
{
    
mciSendString(@"closetemp_alias", null, 0, 0);
    
mciSendString(@"open ""F:\\恋爱ing.mp3""alias temp_alias", null, 0, 0);
    
mciSendString("play temp_aliasrepeat", null, 0, 0);
  
}
     关于mciSendString的详细参数说明,请参见MSDN

    这个方法可以识别一般的文件,比较强大!!

4.使用axWindowsMediaPlayerCOM组件来播放
   a.工具箱->组件->(右键)选择项->COM组件->WindowsMedia Player

   b.Windows Media Player控件拖放到Winform窗体中,把axWindowsMediaPlayer1URL属性设置为MP3或是AVI的文件路径,F5运行。


   如何使用Windows Media Player循环播放列表中的媒体文件?
  假设我们有一个播放列表,下面的代码可以实现自动循环播放

  private void axWindowsMediaPlayer1_PlayStateChange(object sender,AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
 
{
  
if (axWindowsMediaPlayer1.playState ==WMPLib.WMPPlayState.wmppsMediaEnded)
  
{
    
Thread thread = new Thread(newThreadStart(PlayThread));
    
thread.Start();
  
}
 
}
private void PlayThread()
{
  
axWindowsMediaPlayer1.URL = @"E:\Music\SomeOne.avi";
  
axWindowsMediaPlayer1.Ctlcontrols.play();
}







欢迎光临 四联光电智能照明论坛 (http://5xhome.com/) Powered by Discuz! X3.2