using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace ryCommon
{
///
/// 音频播放类
///
public class SoundPlay
{
[DllImport("winmm.dll", SetLastError = true)]
static extern bool PlaySound(string pszSound, IntPtr hmod, uint fdwSound);
[DllImport("winmm.dll")]
static extern Int32 mciSendString(String command, StringBuilder buffer, Int32 bufferSize, IntPtr hwndCallback);
///
/// 临时音频文件
///
private String m_musicPath = "";
///
///父窗口句柄
///
private IntPtr m_Handle;
///
/// 声音标签
///
[Flags]
public enum SoundFlags
{
/// play synchronously (default)
SND_SYNC = 0x0000,
/// play asynchronously
SND_ASYNC = 0x0001,
/// silence (!default) if sound not found
SND_NODEFAULT = 0x0002,
/// pszSound points to a memory file
SND_MEMORY = 0x0004,
/// loop the sound until next sndPlaySound
SND_LOOP = 0x0008,
/// don’t stop any currently playing sound
SND_NOSTOP = 0x0010,
/// Stop Playing Wave
SND_PURGE = 0x40,
/// don’t wait if the driver is busy
SND_NOWAIT = 0x00002000,
/// name is a registry alias
SND_ALIAS = 0x00010000,
/// alias is a predefined id
SND_ALIAS_ID = 0x00110000,
/// name is file name
SND_FILENAME = 0x00020000,
/// name is resource name or atom
SND_RESOURCE = 0x00040004
}
///
/// 音频播放类
///
/// embedded music file
/// 临时保存的文件位置
/// 父窗口句柄
public SoundPlay(Byte[] Music, string folder_path, IntPtr Handle)
{
try
{
m_Handle = Handle;
m_musicPath = Path.Combine(folder_path, "temp.mp3");
FileStream fs = new FileStream(m_musicPath, FileMode.Create);
fs.Write(Music, 0, Music.Length);
fs.Close();
}
catch (Exception)
{
}
}
///
///音频播放类
///
/// 要播放的音频位置
/// 父窗口句柄
public SoundPlay(String musicPath, IntPtr Handle)
{
m_musicPath = musicPath;
m_Handle = Handle;
}
///
/// 音频播放类
///
///
/// 父窗口句柄
public SoundPlay(Byte[] Music, IntPtr Handle) : this(Music, @"C:\Windows\",Handle)
{
}
[DllImport("Kernel32", CharSet = CharSet.Auto)]
static extern Int32 GetShortPathName(String path, StringBuilder shortPath, Int32 shortPathLength);
///
/// 播放音频
///
///
public void Play(string path)
{
if(path != "" && System.IO.File.Exists(path))
{
try
{
string ext = System.IO.Path.GetExtension(path).ToLower();
if (ext == ".mp3")
{
StringBuilder shortpath = new StringBuilder(260);
int result = GetShortPathName(path, shortpath, shortpath.Capacity);
mciSendString(@"close all", null, 0, m_Handle);
mciSendString("open " + shortpath.ToString() + " alias song", null, 0, m_Handle);
mciSendString("play song", null, 0, m_Handle);
}
else if (ext == ".wav")
{
PlaySound(path, m_Handle,(uint)(SoundFlags.SND_FILENAME | SoundFlags.SND_SYNC | SoundFlags.SND_NOSTOP));
}
}
catch (Exception)
{
}
}
}
///
/// 播放音频
///
public void Play()
{
Play(m_musicPath);
}
///
/// 关闭音频
///
void CloseMedia()
{
try
{
mciSendString("Close ALL", null, 0, m_Handle);
}
catch (Exception)
{
}
}
}
}