【发布时间】:2011-05-06 18:11:08
【问题描述】:
如何从项目的资源中播放 WAV 音频文件?我的项目是 C# 中的 Windows 窗体应用程序。
【问题讨论】:
标签: c# visual-studio audio
如何从项目的资源中播放 WAV 音频文件?我的项目是 C# 中的 Windows 窗体应用程序。
【问题讨论】:
标签: c# visual-studio audio
Stream str = Properties.Resources.mySoundFile;
RecordPlayer rp = new RecordPlayer();
rp.Open(new WaveReader(str));
rp.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();。
【讨论】:
这两行可以做到:
SoundPlayer sound = new SoundPlayer(Properties.Resources.solo);
sound.Play();
【讨论】:
据我所知,有两种方法可以做到这一点,请在下面列出:
先把文件放到项目的根目录下,然后不管你在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();
这种方式的优势在于:
运行程序时只需要复制“bin”目录下的“Release”文件夹即可。
【讨论】:
a) 好的,首先将音频文件 (.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)并享受您的声音。
一切顺利。 :)
【讨论】:
因为mySoundFile 是Stream,您可以利用SoundPlayer 的重载构造函数,它接受Stream 对象:
System.IO.Stream str = Properties.Resources.mySoundFile;
System.Media.SoundPlayer snd = new System.Media.SoundPlayer(str);
snd.Play();
【讨论】:
SoundPlayer 构造函数的重载。
当声音仍在播放时,您需要小心垃圾收集器释放声音使用的内存。虽然它很少发生,但当它发生时,你只是在玩一些随机记忆。有一个解决方案,完整的源代码可以在这里实现你想要的:http://msdn.microsoft.com/en-us/library/dd743680(VS.85).aspx
滚动到最底部的“社区内容”部分。
【讨论】: