C#定义的MP3播放类实例
本文实例讲述了C#定义的MP3播放类。分享给大家供大家参考。具体分析如下:
这里使用C#定义一个MP3播放类,将Mp3文件作为资源文件包含到项目中,就可以播放mp3了
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.IO;
usingSystem.Runtime.InteropServices;
namespaceMp3Tool
{
publicClassMP3Player
{
[DllImport("winmm.dll")]
staticexternInt32mciSendString(Stringcommand,StringBuilderbuffer,Int32bufferSize,IntPtrhwndCallback);
///<summary>
///temporaryrepositoryofmusicfiles
///</summary>
privateStringm_musicPath="";
///<summary>
///parentwindowhandle
///</summary>
privateIntPtrm_Handle;
///<summary>
///CreateMp3playerclass
///</summary>
///<PARAMname="music">embeddedmusicfile</param>
///<PARAMname="path">temporarymusicfilepath</param>
///<PARAMname="Handle">parentwindowhandle</param>
publicMP3Player(Byte[]Music,Stringpath,IntPtrHandle)
{
try
{
m_Handle=Handle;
m_musicPath=Path.Combine(path,"temp.mp3");
FileStreamfs=newFileStream(m_musicPath,FileMode.Create);
fs.Write(Music,0,music.Length);
fs.Close();
}
catch(Exception)
{
}
}
///<summary>
///CreateMp3playerclass
///</summary>
///<PARAMname="musicPath">toplaythemp3filepath</param>
///<PARAMname="Handle">parentwindowhandle</param>
publicMP3Player(StringmusicPath,IntPtrHandle)
{
m_musicPath=musicPath;
m_Handle=Handle;
}
publicMP3Player(Byte[]Music,IntPtrHandle):this(Music,@"C:\Windows\",Handle)
{
}
publicvoidOpen(Stringpath)
{
IF(path!="")
{
try
{
mciSendString("Open"+path+"aliasMedia",null,0,m_Handle);
mciSendString("playMedia",null,0,m_Handle);
}
catch(Exception)
{
}
}
}
publicvoidOpen()
{
Open(m_musicPath);
}
voidCloseMedia()
{
try
{
mciSendString("CloseALL",null,0,m_Handle);
}
catch(Exception)
{
}
}
}
}
调用方法:
privatevoidMain()
{
//loadmusic
MP3PlayerMP3=newMP3Player(Properties.Resources.music,Handle);
//musicstartplaying
mp3.Open();
}
希望本文所述对大家的C#程序设计有所帮助。