使用SoundPlayer播放嵌入的wav文件

时间:2009-11-30 18:43:23

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

我有一个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文件的方式有什么问题吗?这是我第一次尝试这样的事情,所以我愿意接受改进建议。

1 个答案:

答案 0 :(得分:3)

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

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

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

如果您需要找到“您在哪里”来创建资源的路径,请参阅this question的答案。

相关问题