【问题标题】:playing .wav file with C#用 C# 播放 .wav 文件
【发布时间】:2019-01-24 10:29:38
【问题描述】:

我正在尝试播放位于我项目内文件夹中的 .Wav 文件。

声音文件位于“Resource/Sounds/slot_roll_on.Wav”

资源文件夹是我自己创建的文件夹,在项目的根目录下。

这是我用来运行 .wav 文件的代码

        Assembly a = Assembly.GetExecutingAssembly();
        Stream s = a.GetManifestResourceStream("kisscam.g.resources.Resources.Sounds.slot_roll_on.wav");
        SoundPlayer snd = new SoundPlayer(s);
        snd.Play();

我无法播放声音,我不断收到 windows 声音,因为找不到声音。

在堆栈溢出的某个地方,我找到了这段代码来找到正确的汇编路径。

            Assembly a = Assembly.GetExecutingAssembly();
            string[] resourceNames = Assembly.GetExecutingAssembly().GetManifestResourceNames();
            int i;
            for (i = 0; i < resourceNames.Length; i++)
            {

                MessageBox.Show(resourceNames[i]);


            }

输出这两条路径

kisscam.Properties.Resources.resources

kissscam.g.resources

我尝试使用它们,但它们都不起作用。

有人知道我做错了什么吗?

【问题讨论】:

  • 试着修改你的问题:)
  • 是的,对不起,我的英语不是很好。你不明白什么?
  • 使用 ildasm.exe 并查看 .mresource 名称的程序集清单。
  • 看起来您的 WAV 文件实际上并未作为资源添加。确保文件已添加到您的项目中,并且构建操作显示“嵌入式资源”
  • @Spedax,我明白了,试着格式化你的问题,这只是一个练习:)

标签: c#


【解决方案1】:

通过转到您的项目属性-> 资源将您的 Wav 文件添加到资源中,然后选择音频并浏览到该文件。然后,您将能够看到它作为 pf Propeties.Resources 的一部分。它会将其添加到资源文件夹中,您可以在其中将其设置为嵌入或保持原样,即设置为内容

这样访问

private void button1_Click(object sender, EventArgs e)
{
    SoundPlayer snd = new SoundPlayer( Properties.Resources.tada);
    snd.Play();

}

【讨论】:

    【解决方案2】:

    如果您想通过在项目中播放 .wav 文件来在程序中添加音乐。然后你必须像这样添加 .wav 文件。

       using System.Media; //  write down it at the top of the FORM
    
       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
    

    请记住,您必须使用正斜杠(/)格式编写文件的路径,在给出路径时不要使用反斜杠()文件,否则会报错

    【讨论】:

      【解决方案3】:

      目前我知道两种方法,见下文:

      1. 使用文件路径
        先把文件放到工程的根目录下,然后不管你是在Debug还是Release模式下运行程序,都可以肯定能访问到文件。接下来使用 SoundPlayer 类来播放它。

            var basePath = System.AppDomain.CurrentDomain.BaseDirectory;
            SoundPlayer player = new SoundPlayer();
            player.SoundLocation = Path.Combine(basePath, @"./../../Reminder.wav");
            player.Load();
            player.Play();
        
      2. 使用资源
        按照下面的动画,将“现有文件”添加到项目中。

              SoundPlayer player = new SoundPlayer(Properties.Resources.Reminder);
              player.Play();
      

      这种方式与其他方式相比的优势在于:
      运行程序时只需要复制“bin”目录下的“Release”文件夹即可。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多