2012-03-11 23 views
0

基本上我有一个声音效果,当两个项目在我的游戏中相撞时播放。有些项目彼此非常接近,所以声音效果可能必须快速连续播放。允许XNA SoundEffectInstance自己播放

使用SoundEffect.Play()可以使用。但是为了保存垃圾收集,我想使用一个实例。不幸的是,这意味着一个实例不会播放,直到最后一个播放完毕。这不是我所追求的效果。有什么方法可以重写这个功能,否则我必须返回普通的旧SoundEffect?

+0

可能重复[从一个实例重复声音](http://stackoverflow.com/questions/8994292/repeating-sound-from-one-instance) – 2014-05-08 01:59:45

回答

1

你有什么理由要“节省垃圾收集?”除非你开始遇到实际的性能问题,否则很可能不需要担心它。根据个人经验,您可以快速连续播放至少一打声音(使用SoundEffect.Play()),不会有任何问题。然而,如果你觉得你的游戏有很多碰撞,你可以做两件事:

首先,考虑创建一个简单的SoundPlayer类来处理所有你玩的声音,并且每当你发现超过10个同时玩的时候,防止下一个被玩。如果发生很多碰撞,玩家不会注意到缺少声音。

其次,请看这里(http://forums.create.msdn.com/forums/t/91165.aspx)关于如何使用DynamicSoundEffectInstance来预混声音。这有点复杂一些,但通过展望未来,将所有即将播放的声音混合到单个缓冲区中,几乎可以保证零延迟,因为只有一个声音(或一个音频流缓冲区)有效播放。

+0

啊,如果没有简单的方法来做它可能它精细。在我的游戏中,它不可能同时发生10次或更多次的碰撞,所以我会留下它与正常SoundEffect.Play()的关系。感谢您的想法。 – DanTonyBrown 2012-03-11 16:34:46

0
List<SoundEffectInstance> explosionSoundInstanceList; 


     explosionSound = Content.Load<SoundEffect>("sound/explosion"); 

     explosionSoundInstanceList = new List<SoundEffectInstance>(MAX_EXPLOSIONS); 

     for (int i = 0; i < MAX_EXPLOSIONS; i++) 
     { 
      explosionSoundInstanceList.Add(explosionSound.CreateInstance()); 
     } 



private void PlayExplosionSound(float volume, float pitch, float pan) 
    { 

     ClampSoundValues(ref volume, ref pitch, ref pan); 

     for (int i = 0; i < explosionSoundInstanceList.Count; i++) 
     { 
      if (explosionSoundInstanceList[i].State == SoundState.Stopped) 
      { 
       explosionSoundInstanceList[i].Volume = volume/(i+1); 
       explosionSoundInstanceList[i].Pitch = pitch; 
       explosionSoundInstanceList[i].Pan = pan; 
       explosionSoundInstanceList[i].Play(); 
       return; 
      } 

     } 

     return; 
    } 

工作正常。 实例化后的360上的零垃圾。 你达到极限后会失败。

这就是我使用的。

我钳位值正是如此

private static void ClampSoundValues(ref float volume, ref float pitch, ref float pan) 
    { 
     volume = MathHelper.Clamp(volume, -1f, 1f); 
     pitch = MathHelper.Clamp(pitch, -1f, 1f); 
     pan = MathHelper.Clamp(pan, -1f, 1f); 
    } 

由于设置一个愚蠢的价值将下降一个例外。