如何从Resources播放WAV音频文件?

Gen*_*ius 36 c# audio visual-studio

如何从我的项目资源中播放WAV音频文件?我的项目是C#中的Windows窗体应用程序.

Eva*_*ski 48

因为mySoundFile是a Stream,你可以利用SoundPlayer重载的构造函数,它接受一个Stream对象:

System.IO.Stream str = Properties.Resources.mySoundFile;
System.Media.SoundPlayer snd = new System.Media.SoundPlayer(str);
snd.Play();
Run Code Online (Sandbox Code Playgroud)

SoundPlayer类文档(MSDN)

  • @TomeeNS:当然,它向人们展示了资源的类型和使用的`SoundPlayer`构造函数的重载. (4认同)
  • 这将在Windows CE中引发异常,因为它不会自动将资源从byte []转换为流.我发现在这种情况下有以下答案.将它留给其他人:http://stackoverflow.com/questions/1900707/how-to-play-audio-from-resource (2认同)

Pra*_*ran 44

a)好的,首先将音频文件(.wav)添加到项目资源中.

  1. 从菜单工具栏("VIEW")打开"Solution Explorer"或只需按Ctrl + Alt + L.
  2. 单击"属性"的下拉列表.
  3. 然后选择"Resource.resx"并按Enter键.

打开项目资源

  1. 现在从组合框列表中选择"音频".

将音频文件添加到资源

  1. 然后单击"添加资源",选择音频文件(.wav)并单击"打开".

浏览音频文件

  1. 选择音频文件并将"Persistence"属性更改为"Embedded in .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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

而已.
全部完成,现在运行项目(按f5)并享受你的声音.
祝一切顺利.:)


Ale*_*eks 8

  Stream str = Properties.Resources.mySoundFile;
  RecordPlayer rp = new RecordPlayer();
  rp.Open(new WaveReader(str));
  rp.Play();
Run Code Online (Sandbox Code Playgroud)

如何从C#中的资源播放WAV音频文件.