前段时间用到在C#中调用函数实现播放功能,现将代码总结下:
网上找到的播放单元的代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace MediaPlay
{
public class MediaPlays
{
[DllImport("WinMM.dll")]
public static extern bool PlaySound(byte[]wfname, int fuSound);
public int SND_SYNC = 0x0000;
public int SND_ASYNC = 0x0001;
public int SND_NODEFAULT = 0x0002;
public int SND_MEMORY = 0x0004;
public int SND_LOOP = 0x0008;
public int SND_NOSTOP = 0x0010;
public int SND_NOWAIT = 0x00002000;
public int SND_ALIAS = 0x00010000;
public int SND_ALIAS_ID = 0x00110000;
public int SND_FILENAME = 0x00020000;
public int SND_RESOURCE = 0x00040004;
public int SND_PURGE = 0x0040;
public int SND_APPLICATION = 0x0080;
//-----------------------------------------------------------------
public void Play(string wfname,int SoundFlags)
{
byte[] bname = new Byte[256];
bname = System.Text.Encoding.ASCII.GetBytes(wfname);
PlaySound(bname,SoundFlags);
}
//-----------------------------------------------------------------
public void StopPlay()
{
PlaySound(null,SND_PURGE);
}
}
}
自己封装的播放单元:
using System;
using System.Runtime.InteropServices;
using System.Resources;
using System.IO;
namespace YJZS_Demo
{
public class Winmm
{
public const UInt32 SND_ASYNC = 1;
public const UInt32 SND_MEMORY = 4;
public const UInt32 SND_PURGE = 0x0040;
static FileStream str = null;
// these 2 overloads we dont need ...
// [DllImport("Winmm.dll")]
// public static extern bool PlaySound(IntPtr rsc, IntPtr hMod, UInt32 dwFlags);
// [DllImport("Winmm.dll")]
// public static extern bool PlaySound(string Sound, IntPtr hMod, UInt32 dwFlags);
// this is the overload we want to play embedded resource...
[DllImport("Winmm.dll")]
public static extern bool PlaySound(byte[] data, IntPtr hMod, UInt32 dwFlags);
public Winmm()
{
}
public static void PlayWavResource(string wav)
{
// get the namespace
string strNameSpace =
System.Reflection.Assembly.GetExecutingAssembly().GetName().Name.ToString();
// get the resource into a stream
//Stream str = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(strNameSpace + "." + wav);
//Stream str = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(wav);
str = new FileStream(wav, FileMode.Open);
if (str == null)
return;
// bring stream into a byte array
byte[] bStr = new Byte[str.Length];
str.Read(bStr, 0, (int)str.Length);
// play the resource
PlaySound(bStr, IntPtr.Zero, SND_ASYNC | SND_MEMORY);
}
public static void StopPlay()
{
PlaySound(null, IntPtr.Zero, SND_PURGE);
if (str != null)
{
str.Close();
str = null;
}
}
}
}
在一个页面的datagrid中调用Winmm类的方法:
using MediaPlay;
private void dgv1_CellClick(object sender, DataGridViewCellEventArgs e)
{
switch (e.ColumnIndex)
{
case 8:
{
Winmm.StopPlay();
Winmm.PlayWavResource("pt101.wav");
break;
}
case 9:
{
Winmm.StopPlay();
break;
}
}
}