C#播放音乐的5种方式

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音乐文件

System.Media.SoundPlayer sp = new SoundPlayer();
sp.SoundLocation = @"D:\TestMusic.wav"; //音乐文件
sp.PlayLooping();

3. 使用非托管的dll播放.wav音乐文件

using System.Runtime.InteropServices;

class PlayMusic
{  
    [DllImport("winmm.dll")]
    public static extern bool PlaySound(String Filename,int Mod,int Flags);
  
    public void Main()
    {  
        PlaySound(@"D:\TestMusic.wav", 0, 1); //第3个形参,把1换为9,连续播放
    }
}

4. 使用MCI Command String多媒体设备程序接口播放.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 ""D:\TestMusic.mp3"" alias temp_alias", null, 0, 0); //音乐文件
  mciSendString("play temp_alias repeat", null, 0, 0);
}

5. 使用axWindowsMediaPlayer的COM组件播放.mp3或.avi音乐文件

       1) 加载COM组件:ToolBox->Choose Items->COM Components->Window Media Player。

       2) 把Windows Media Player控件拖到窗体中,把axWindowsMediaPlay1的URL属性设置为.mp3或.avi音乐文件的路径,运行程序即可。

       3) 使用Windows Media Player循环播放音乐文件:

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 = @"D:\TestMusic.avi"; //音乐文件
  axWindowsMediaPlayer1.Ctlcontrols.play();
}

       赶紧动手设计一个简易的音乐播放器吧!只要坚持每天一点点地改进你的音乐播放器,不断地增加新的功能,相信总有一天它会成为最适合你的音乐播放器。

  • 6
    点赞
  • 51
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值