代码之家  ›  专栏  ›  技术社区  ›  Brandon

使用SoundPlayer播放嵌入的wav文件

  •  1
  • Brandon  · 技术社区  · 16 年前

    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();
        }
    }
    

    这样做的目的不是每次扫描条形码时(一小时几百次)都创建一个声音播放器。所以我可以对已经加载的文件调用Play。

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

    1 回复  |  直到 16 年前
        1
  •  3
  •   Community Mohan Dere    9 年前

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

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

    this question .

    推荐文章