c# - 在 C# 中嵌入声音

标签 c# visual-studio-2010 audio

我知道有很多线程具有相同的主题,但由于我还不明白的原因,这对我不起作用。

我有这个项目树:

Project Tree

我从“项目”->“属性”->“资源”菜单将 Alarm.wav 嵌入到 .resx 文件中。

我尝试了不同的代码组合,但没有任何效果。

目前这是我正在尝试的代码。

using System;
using System.Media;
using System.Windows.Forms;
using System.Threading;
using System.Globalization;
using System.ComponentModel;
using System.Resources;
using AlarmForm;

namespace Alarm
{
    public partial class Form1 : Form
    {
        private bool estado = false;
        private SoundPlayer sonido;

        public Form1()
        {
            InitializeComponent();
            ResourceManager resources = new ResourceManager(typeof(Form1));
            sonido = new SoundPlayer(resources.GetStream("alarma"));
        }
    }
}

在编译或运行时不会显示任何错误,但听到的不是声音而是错误蜂鸣声。

已编辑:尝试使用 Alarm.Properties 时发现错误

Alarm.Properties Error

最佳答案

当您可以使用Alarm.Properties直接链接文件时,为什么要尝试使用resources.GetStream()?我相信这会容易得多。我发现您还忘记播放链接到 sonido 的声音文件,该文件代表新的 SoundPlayer。这是一个简单的示例,展示了如何使用 SoundPlayer

示例

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Resources;
using System.Media;
using AlarmForm.
using AlarmForm.Properties; //Required to call 'Resources' directly

namespace Alarm
{
    public partial class Form1 : Form
    {
        private bool estado = false;
        private SoundPlayer sonido;

        public Form1()
        {
            InitializeComponent();
            //ResourceManager resources = new ResourceManager(typeof(Form1)); //We do not actually need this
            sonido = new SoundPlayer(Resources.alarma); //Initialize a new SoundPlayer linked to our sound file (or Alarm.Properties.Resources.alarma if Alarm.Properties was not imported)
            sonido.Play(); //Required if you would like to play the file
        }
    }
}

请注意:您可以随时通过 sonido.Stop() 停止 SoundPlayer 播放,因为 sonido > 表示名称为 SoundPlayer 的新类在 public 分部类 Form1: Form 下定义,除非尝试调用 sonido 的 void 是静态。

谢谢,
希望您觉得这有帮助:)

关于c# - 在 C# 中嵌入声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13187727/

相关文章:

C# (ASP.Net) 将选择值链接到代码隐藏中的常量

c++ - 在 C++ 代码中使用 K&R 风格的 C 函数

c++ - 如何一劳永逸地在VS中设置配置属性?

c++ - 从 C/C++ 播放声音的最简单方法

c# - 使用 .Netcore 库的 FxCop 分析在 VS2015 更新 3 中失败

c# - Selenium native android 应用程序的 DesiredCapabilities 已过时

javascript - 使用 Nodejs 捕获系统音频输出

audio - 如何将 24 位音频流传送到图形?

c# - ASP.Net 静态值在刷新页面时不断累积

visual-studio-2010 - 如何在 Visual C# 项目类型节点之外创建项目模板节点?