我该如何在我的项目资源中播放WAV音频文件?我的项目是一个使用C#编写的Windows窗体应用程序。
我该如何在我的项目资源中播放WAV音频文件?我的项目是一个使用C#编写的Windows窗体应用程序。
由于mySoundFile
是一个Stream
对象,您可以利用SoundPlayer
的重载构造函数,该构造函数接受一个Stream
对象:
System.IO.Stream str = Properties.Resources.mySoundFile;
System.Media.SoundPlayer snd = new System.Media.SoundPlayer(str);
snd.Play();
SoundPlayer
构造函数的类型和负载。 - Evan Mulawskia) 好的,首先将音频文件(.wav)添加到项目资源中。
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键),享受你的声音。
祝一切顺利。 :)
Stream str = Properties.Resources.mySoundFile;
RecordPlayer rp = new RecordPlayer();
rp.Open(new WaveReader(str));
rp.Play();
Theses two lines can do it:
SoundPlayer sound = new SoundPlayer(Properties.Resources.solo);
sound.Play();
当您需要将声音添加到项目中时,可以通过播放.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.PlaySync();
更改为my_wave_file.PlayAsync();
。
据我所知,有两种方法可以实现,如下所示:
首先将文件放置在项目的根目录中,然后无论您在 Debug
或 Release
模式下运行程序,该文件都可以被访问。然后使用 SoundPlayer
类来播放它。
但是,这种方式需要将声音文件与其文件夹层次结构复制到除了 "bin" 目录下的 "Release" 文件夹层次结构之外的所有文件夹层次结构中,如果您想将项目发布给用户。
var basePath = System.AppDomain.CurrentDomain.BaseDirectory;
SoundPlayer player = new SoundPlayer();
player.SoundLocation = Path.Combine(basePath, @"./../../Reminder.wav");
player.Load();
player.Play();
按照下面的动画,将“现有文件”添加到项目中。
SoundPlayer player = new SoundPlayer(Properties.Resources.Reminder);
player.Play();