先添加命名空间。
using System.Runtime.InteropServices
调用时候用 Sound.Play(文件路径);
文件路径也可以把声音文件放在DEBUG目录下,然后
string sound=System.Windows.Forms.Application.StartupPath +@"sound.wav";
调用 Sound.Play(sound);
internal class Helpers
{
[Flags]
public enum PlaySoundFlags : int
{
SND_SYNC = 0x0000,
SND_ASYNC = 0x0001,
SND_NODEFAULT = 0x0002,
SND_MEMORY = 0x0004,
SND_LOOP = 0x0008,
SND_NOSTOP = 0x0010,
SND_NOWAIT = 0x00002000,
SND_ALIAS = 0x00010000,
SND_ALIAS_ID = 0x00110000,
SND_FILENAME = 0x00020000,
SND_RESOURCE = 0x00040004
}
[DllImport("winmm.dll")]
public static extern bool PlaySound( string szSound, IntPtr hMod, PlaySoundFlags flags );
}
public class Sound
{
public static void Play( string strFileName )
{
Helpers.PlaySound( strFileName, IntPtr.Zero, Helpers.PlaySoundFlags.SND_FILENAME | Helpers.PlaySoundFlags.SND_ASYNC );
}
}
{
[Flags]
public enum PlaySoundFlags : int
{
SND_SYNC = 0x0000,
SND_ASYNC = 0x0001,
SND_NODEFAULT = 0x0002,
SND_MEMORY = 0x0004,
SND_LOOP = 0x0008,
SND_NOSTOP = 0x0010,
SND_NOWAIT = 0x00002000,
SND_ALIAS = 0x00010000,
SND_ALIAS_ID = 0x00110000,
SND_FILENAME = 0x00020000,
SND_RESOURCE = 0x00040004
}
[DllImport("winmm.dll")]
public static extern bool PlaySound( string szSound, IntPtr hMod, PlaySoundFlags flags );
}
public class Sound
{
public static void Play( string strFileName )
{
Helpers.PlaySound( strFileName, IntPtr.Zero, Helpers.PlaySoundFlags.SND_FILENAME | Helpers.PlaySoundFlags.SND_ASYNC );
}
}
本文介绍了一种使用C#在Windows环境下播放音频文件的方法。通过调用winmm.dll中的PlaySound函数,并定义PlaySoundFlags枚举来控制播放行为,如同步或异步播放等。
2万+

被折叠的 条评论
为什么被折叠?



