一个简单的类,允许你在 C# 中播放 Wav 文件






2.89/5 (24投票s)
2004年4月15日
1分钟阅读

114425

1781
据我所见,框架中没有播放声音的函数。因此,在四处寻找并收集如何操作的信息后,我最终创建了一个类。我喜欢将其用于错误消息。我只是导入了 DLL 文件 winmm.dll,并从中使用了 PlaySound 函数。
引言
tonysound.cs 类使你能够在 Windows 窗体中添加 Wav 音频。只需将 tonysound.cs 包含在你的项目文件夹中。这是我的第一篇文章,请不要太苛刻。
在你的窗体中包含代码
将 tonysound.cs 文件添加到你的项目中。然后在调用窗体的顶部,例如 form1
,输入以下行以使用 tonysound
类。
using tonysound;
一旦包含 using tonysound;
,只需通过调用来播放声音
Sound.Play(stringOfFilename,PlaySoundFlags.selectaflaghere );
注意:你可以传递任意数量的标志,但如果你正在播放文件,则需要像我在代码中所做的那样执行操作。
Sound.Play("sound.wav",PlaySoundFlags.SND_FILENAME);
Sound.Play
的第一个参数是文件名。文件名可以是实际路径,例如 c:\\sound.wav,也可以是与 exe 文件位于同一目录中的 Wav 文件。第二个是播放声音的标志。你可以播放空声音来关闭声音,如下所示
Sound.Play(null,null);
注意:你必须包含 PlaySoundFlags.SND_FILENAME
或 PlaySoundFlags.SND_RESOURCE
才能实际播放歌曲。其余标志是可选的。
PlaySoundFlags 及其用途列表
SND_SYNC //plays the sound after the event for example a button being pushed
SND_ASYNC //play sound as soon as event happens
SND_NODEFAULT //don't play the default sound if the soundsource is not found
SND_LOOP //play the wav over and over
SND_NOSTOP //don't stop any currently playing sound
SND_NOWAIT //don't wait if the sound driver is busy
SND_RESOURCE //indicates you are using a wav from a resource
SND_FILENAME //indicates you are using a wav from a file source
这些是对我先前帖子的修改,感谢大家的建议。