【问题标题】:Playing embedded wav files using SoundPlayer使用 SoundPlayer 播放嵌入的 wav 文件
【发布时间】:2010-12-21 18:04:09
【问题描述】:

我有一个 Compact Framework 3.5 应用程序,负责扫描条形码。根据情况,它应该播放 3 种不同的声音,因此我围绕 SoundPlayer 对象创建了一个包装类,并在其上调用 Play 方法。

public static class SoundEffectsPlayer
{
    private static readonly SoundEffect _alert;

    static SoundEffectsPlayer()
    {
        // This will cause the SoundEffect class to throw an error that the Uri 
        // Format is not supported, when new SoundPlayer(location) is called.
        _alert = new SoundEffect("SoundEffects/alert.wav");
    }

    public static SoundEffect Alert
    {
        get { return _alert; }
    }
}

public class SoundEffect
{
    private readonly SoundPlayer _sound;

    public SoundEffect(string location)
    {
        _sound = new SoundPlayer(location);
        _sound.Load();
    }

    public bool IsLoaded
    {
        get { return _sound.IsLoadCompleted; }
    }

    public void Play()
    {
        _sound.Play();
    }
}

我们的想法是不要在每次需要扫描条形码时都创建 SoundPlayer(每小时扫描几百次)。所以我可以在已经加载的文件上调用 Play 。

alert.wav 文件位于应用程序引用的库项目根目录中的 SoundEffects 文件夹中,并且它被设置为嵌入式资源。我需要将什么传递给 SoundEffects 类来加载 wav 文件?是否应该将 wav 文件嵌入到库项目中?

还有人注意到我处理 wav 文件播放的方式有什么问题吗?这是我第一次尝试这样的事情,所以我愿意接受改进建议。

【问题讨论】:

    标签: c# compact-framework embedded-resource soundplayer


    【解决方案1】:

    嗯。我以前没有使用过 SoundPlayer,我猜它只是 coredll 函数 PlaySound 的一个包装器。但无论如何,我希望它需要一个文件路径作为参数。

    因此,要使其与嵌入式资源一起使用,您可能必须将文件保存到磁盘然后播放。放弃嵌入式资源的想法并将其部署为单独的项目可能会更简单。将 .wav 包含在您的主项目中,将其设置为:“内容”和“如果较新则复制”,然后在声音播放器调用中将其作为文件引用。

    请记住,在 WindowsCE 中,您也总是需要完整路径。当前运行的 .exe 的相对路径在 CE 中不起作用。

    如果您需要找出“您所在的位置”来创建资源的路径,请参阅this question 的答案。

    【讨论】:

      猜你喜欢
      • 2012-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      • 2014-04-01
      • 1970-01-01
      相关资源
      最近更新 更多