我知道有很多线程具有相同的主题,但由于我还不明白的原因,这对我不起作用。
我有这个项目树:
我从“项目”->“属性”->“资源”菜单将 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
直接链接文件时,为什么要尝试使用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/