最近在做一个监控项目的时候要求在监控的时候可以采用声音告警,如果用的是VS那么直接调用Media player好了,可惜自己用的是#Develop做为开发环境。居然不支持com组件的引用。我倒~
于是参照MS API写了下面这个简单的播放类
/*
* Created by SharpDevelop.
* User: root
* Date: 2006-8-16
* Time: 15:44
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Runtime.InteropServices;
namespace Com.Music
{
/// <summary>
/// 音乐播放类
/// 参考:http://msdn.microsoft.com/library/default.asp?url=/library/en-us/multimed/htm/_win32_multimedia_command_strings.asp
/// </summary>
public class MusicPlayer
{
[DllImport("winmm.dll")]
private static extern long mciSendString(string strCommand,
string strReturn, int iReturnLength, IntPtr hwndCallback);
public MusicPlayer()
{
}
//播放器状态
/*
*
* All devices can return the
* "not ready", "paused", "playing", and "stopped" values.
* Some devices can return the additional
* "open", "parked", "recording", and "seeking" values
*
*/
public string Status
{
get{
string sCommand = "status MediaFile mode";
string ret="";
mciSendString(sCommand, ret, 10, IntPtr.Zero);
return ret.Trim();
}
}
private void Open(string sFileName)
{
string sCommand="open /"" + sFileName + "/" type mpegvideo alias MediaFile";
// MediaFile是选择播放文件类型
string ret=null;
mciSendString(sCommand, ret, 0, IntPtr.Zero);
}
//播放音乐
public void Play(string filename)
{
Open(filename);
string sCommand = "play MediaFile";
string ret=null;
mciSendString(sCommand,ret, 0, IntPtr.Zero);
}
//停止播放音乐
public void Stop()
{
string sCommand = "stop MediaFile";
string ret=null;
mciSendString(sCommand, ret, 0, IntPtr.Zero);
}
public void Pause()
{
string sCommand = "pause MediaFile";
string ret=null;
mciSendString(sCommand, ret, 0, IntPtr.Zero);
}
}
}
播放的话只要一句就搞定
MusicPlayer mp = new MusicPlayer();
void Button1Click(object sender, System.EventArgs e)
{
mp.Play("H:/mp3/十七岁的雨季.mp3");
}
另外拿这个测试拉下MONO 1.6 beta 还不错开来MONO也开始支持调用OS本地API了。