目录
Step#1 先将Windows Media Player控件添加到工具箱(Toolbox)中
Step#1 先将Windows Media Player控件添加到工具箱(Toolbox)中
OK点击之后会出现在此
Step#2 新建项目
放入两个按钮(Button)和一个Windows Media Player,它们的名称如下截图
Step#3 完整代码
【注意事项】
1. 引用命名空间
using System.Runtime.InteropServices;
2. 引入动态链接库与函数
[DllImport("winmm")]
public static extern bool PlaySound(string szSound, int hMod, int i);
3. 分别双击btnPlaySound和btnPlayMusic添加两个事件btnPlaySound_Click和btnPlayMusic_Click
4. 添加两个函数Play和PlayMusic
5. 将xx.wav与xx.mid音频文件放置在bin/Debug文件夹中
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
// 引入新的命名空间,以调用Windows系统自带的PlaySound函数
using System.Runtime.InteropServices;
namespace Ex3_7PalySound
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// 引入动态链接库
[DllImport("winmm")]
public static extern bool PlaySound(string szSound, int hMod, int i);
private void Play(string waveName)
{
PlaySound(Application.StartupPath + "\\"+waveName,0,1);
}
private void PlayMusic(string musicName)
{
this.axWindowsMediaPlayer1.URL = "";
this.axWindowsMediaPlayer1.URL = Application.StartupPath + "\\" + musicName;
}
private void btnPlaySound_Click(object sender, EventArgs e)
{
this.Play("Shot.wav");
}
private void btnPlayMusic_Click(object sender, EventArgs e)
{
this.PlayMusic("town.mid");
}
}
}
Step#4 运行效果
【说明】代码选自《C# Windows游戏设计》