在这里主要介绍下3种方法实现(部分介绍还是来自网络 在这里总结下 希望对大家有所帮助)
1.命名空间的添加
using System.Runtime.InteropServices;
using System.IO;
using System.Reflection;
2. 调用类库 内置的
//播放声音
//1
[DllImport("user32.dll ")]
public static extern int MessageBeep(uint n);
//2
/// <param name="iFrequency">声音频率(从37Hz到32767Hz)。在windows95中忽略
</param>
/// <param name="iDuration">声音的持续时间,以毫秒为单位。</param>
[DllImport("Kernel32.dll")] //引入命名空间 using
System.Runtime.InteropServices;
public static extern bool Beep(int frequency, int duration);
//3
//IntPtr soundHandle;//这个没用
public static uint SND_ASYNC = 0x0001;
public static uint SND_FILENAME = 0x00020000;
[DllImport("winmm.dll")]
public static extern int mciSendString(string m_strCmd, string m_strReceive,
int m_v1, int m_v2);
[DllImport("Kernel32", CharSet = CharSet.Auto)]
static extern Int32 GetShortPathName(String path,StringBuilder shortPath,Int32
shortPathLength);
3. 按钮 的调用代码 如下
private void btnjg_Click(object sender, EventArgs e)
{
//第1种 播放内置音响声
for (int i = 0; i < 3; i++)
{
MessageBeep(0xFFFFFFFF); //播放
}
//第2种
//C#调用系统蜂鸣(发出警告时 即使没有声卡,没有外界音响或耳机都行 主要是从主
机发出来的)
// 调用
Beep(900, 500); // 这个声音不错 推荐
try
{
//第3种播放 指定的声音
//调用
StringBuilder shortpath = new StringBuilder(80);
int result = GetShortPathName(strmp3, shortpath, shortpath.Capacity);
// name = shortpath.ToString();
mciSendString(@"close all", null, 0, 0);
mciSendString(@"open " + strmp3 + " alias song", null, 0, 0); //打开
mciSendString("play song", null, 0, 0); //播放
// mciSendString("close song", null, 0, 0); //停止播放
}
catch (Exception ex)
{
}
}