【问题标题】:How to play a sound without creating a new player each time如何在不每次都创建新播放器的情况下播放声音
【发布时间】:2012-10-23 15:22:58
【问题描述】:

我正在做一个表单项目,并在一些方法和事件中播放一些声音。 例如,在一个方法中我有这个:

SoundPlayer sndplayrONE = new SoundPlayer(Properties.Resources.wavsound1);

sndplayrONE.Play();

在另一个,我有这个:

SoundPlayer sndplayrTWO = new SoundPlayer(Properties.Resources.wavsound2);

sndplayrTWO.Play();

我想要的是在表单代码的开头只创建一个声音播放器类的实例,比如

SoundPlayer sndplayr = new SoundPlayer(--some generic input---)

然后从任何事件中调用它,例如

sndplayr2.Play(sound1); sndplayr2.Play(sound2); sndplayr2.Play(sound3);

等等……

我见过一些构造函数,例如 SoundPlayer(Stream)SoundPlayer(String),但我不明白其中的任何一个。我需要一些简单的东西,就像我以前做的那样,但每次我想播放声音时都不需要创建一个新实例。我在 Resources.resx 中嵌入了所有声音。

【问题讨论】:

  • 每次创建一个新实例对你来说真的那么工作量很大吗?
  • 它不仅可以工作,而且还可以声称效率和代码气味

标签: c# wav audio-player soundplayer


【解决方案1】:

使用不同的构造函数

http://msdn.microsoft.com/en-us/library/system.media.soundplayer.aspx

System.Media.SoundPlayer myPlayer = new System.Media.SoundPlayer();
myPlayer.SoundLocation = @"c:\click.wav";
myPlayer.Play();

【讨论】:

    【解决方案2】:

    在此处查看信息:MSDN SoundPlayer Class (System.Media)

    您似乎可以通过设置 SoundLocation 属性然后执行 Load() 或 LoadAsync() 来更改特定播放器将播放的声音。

    不过,明智的做法是制作一个类似于字典的东西,在其中放入您认为与当前上下文相关的多个 SoundPlayer 对象。比如:

    Dictionary<string, SoundPlayer> sounds;
    
    // Load sounds
    
    // I wouldn't hardcode strings here, use constants or something. This is just an example.
    sound["Sound1"].Play();
    

    【讨论】:

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