【问题标题】:How to play WAV file from Properties.Resources using C#如何使用 C# 从 Properties.Resources 播放 WAV 文件
【发布时间】:2019-01-24 10:27:41
【问题描述】:

如何播放来自Properties.Resources 的 wav 文件?

我尝试了一些代码,但每次我的Priperties.Resource.myFile 将我放入byte[] 但我的代码需要string 路径,而不是byte[] 数组。

    System.Media.SoundPlayer player = new System.Media.SoundPlayer();

    player.SoundLocation = @"myFile.wav";
    player.Play();

我不想使用一些临时文件。可以直接从资源播放吗?

感谢您的建议!

【问题讨论】:

  • SoundPlayer 只能播放 wav 文件
  • 那么,我可以从 Resource 播放 WAV 文件吗?
  • 如果这是你想要的。请更改您的问题以提及 WAV 文件而不是 MP3,以免对其他人造成混淆。

标签: c# wav


【解决方案1】:

据我所知,有两种方法可以做到这一点,见下文:

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

        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”文件夹即可。

【讨论】:

    【解决方案2】:

    那么,我可以从 Resource 播放 WAV 文件吗?

    您可以像这样使用Stream 属性:

    System.Media.SoundPlayer player = new System.Media.SoundPlayer();
    
    player.Stream = new MemoryStream(data);
    player.Play();
    

    其中data 是您从资源文件中获得的byte[]

    更新:

    Properties.Resources.myFile其实应该是一个流,所以直接这样使用:

    System.Media.SoundPlayer player = new System.Media.SoundPlayer();
    
    player.Stream = Properties.Resources.myFile;
    player.Play();
    

    【讨论】:

    • 我试试你的代码,但在new MemoryStream(data); 上我收到错误cannot convert from 'System.IO.UnmanagedMemoryStream' to 'int'
    • dataProperties.Resources.myFile。文件 myFile 是 wav。
    • 感谢您的帮助。完美运行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-09
    • 1970-01-01
    相关资源
    最近更新 更多