如何从资源播放WAV音频文件?
Stream str = Properties.Resources.mySoundFile;
RecordPlayer rp = new RecordPlayer();
rp.Open(new WaveReader(str));
rp.Play();
因为mySoundFile
是Stream
,你可以采取的SoundPlayer
的重载的构造函数,它接受一个Stream
对象的优势:
System.IO.Stream str = Properties.Resources.mySoundFile;
System.Media.SoundPlayer snd = new System.Media.SoundPlayer(str);
snd.Play();
这将在Windows CE中引发异常,因为它不会自动将资源从byte []转换为流。我发现在这种情况下有以下答案。将它留在这里为其他人: http://stackoverflow.com/questions/1900707/how-to-play-audio-from-resource – Hagelt18 2014-12-31 18:21:19
我们实际上不需要申报一个单独的流变量;) – TomeeNS 2016-06-10 00:00:16
@TomeeNS:当然,但它向人们显示资源的类型和所使用的'SoundPlayer'构造函数的重载。 – 2016-06-13 13:51:26
你需要谨慎对待垃圾收集器释放存储器在声音仍在播放时使用的内存。虽然它很少发生,但当它发生时,你只会播放一些随机存储器。有一个解决方案,完成与源代码实现你想在这里:http://msdn.microsoft.com/en-us/library/dd743680(VS.85).aspx
滚动到最底部,在“社区内容”部分。
当您必须将声音添加到您的项目中时,您将通过播放.wav
文件来完成此操作。然后你必须添加这样的.wav
文件。
using System.Media; //write this at the top of the code
SoundPlayer my_wave_file = new SoundPlayer("F:/SOund wave file/airplanefly.wav");
my_wave_file.PlaySync(); // PlaySync means that once sound start then no other activity if form will occur untill sound goes to finish
请记住,你写的文件的路径与正斜杠(/
)格式,不要使用反斜杠(\
)给予文件的路径时,否则你会得到一个错误。
另请注意,如果您希望在播放声音时发生其他事情,则可以使用my_wave_file.PlayAsync();
更改my_wave_file.PlaySync();
。
a)OK,首先将音频文件(.wav)添加到项目资源中。
- 从菜单工具栏(“VIEW”)打开“解决方案资源管理器”或者只需按Ctrl + Alt + L。
- 点击“属性”的下拉列表。
- 然后选择“Resource.resx”并按回车。
- 现在从组合框列表中选择 “音频”。
- 然后点击 “添加资源”,选择的音频文件(.WAV)和点击 “打开”。
- 选择的音频文件(一个或多个)和改变为 “中的.resx嵌入式”, “持续性” 的性质。
b)现在,只写这段代码播放音频。
在这段代码中,我在表单加载事件上播放音频。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Media; // at first you've to import this package to access SoundPlayer
namespace WindowsFormsApplication1
{
public partial class login : Form
{
public login()
{
InitializeComponent();
}
private void login_Load(object sender, EventArgs e)
{
playaudio(); // calling the function
}
private void playaudio() // defining the function
{
SoundPlayer audio = new SoundPlayer(WindowsFormsApplication1.Properties.Resources.Connect); // here WindowsFormsApplication1 is the namespace and Connect is the audio file name
audio.Play();
}
}
}
就是这样。
全部完成,现在运行该项目(按f5)并享受您的声音。
一切顺利。 :)
正是我在找的东西!照片帮了很多。你知道我是否可以用这种方式嵌入字体(如fontawesome)以及在我的程序中使用? – 2016-08-02 19:52:15
当我添加一个wav文件时,它添加了一个Resources2.Designer.cs,它似乎是Resources.Designer.cs的一个重复项 - 从而给我带来冲突。这刚刚开始发生。任何想法可能发生什么? https://www.screencast.com/t/xAVpE5v6b0 – Matt 2017-12-07 22:05:21
[这是你正在寻找。](http://msdn.microsoft.com/en-us/library/3w5b27z4.aspx) – 2010-11-08 16:23:39