gpt4 book ai didi

c# - 在 C# 中嵌入声音

转载 作者:太空宇宙 更新时间:2023-11-03 11:14:05 25 4
gpt4 key购买 nike

我知道有很多讨论主题相同,但出于某种我还不明白的原因,这对我不起作用。

我有这个项目树:

Project Tree

我从 Project->Properties->Resources 菜单将 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

最佳答案

为什么要尝试使用 resources.GetStream() 而您可以使用 Alarm.Properties 直接链接文件?我相信这会容易得多。我看到您还忘记播放链接到 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 表示一个新的名称类 SoundPlayer 是在 public partial class Form1: Form 下定义的,除非尝试调用 sonido 的 void 是静态。

谢谢,
希望这对您有所帮助:)

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com