2011-12-14 48 views
3

我需要在我的應用程序中反覆播放單個聲音,例如,使用XAudio2進行槍擊。如何與XAudio2重複播放相同的聲音?

這是我寫用於該目的的代碼的一部分:

public sealed class X2SoundPlayer : IDisposable 
    { 
     private readonly WaveStream _stream; 
     private readonly AudioBuffer _buffer; 
     private readonly SourceVoice _voice; 

     public X2SoundPlayer(XAudio2 device, string pcmFile) 
     { 
      var fileStream = File.OpenRead(pcmFile); 
      _stream = new WaveStream(fileStream); 
      fileStream.Close(); 

      _buffer = new AudioBuffer 
          { 
           AudioData = _stream, 
           AudioBytes = (int) _stream.Length, 
           Flags = BufferFlags.EndOfStream 

          }; 

      _voice = new SourceVoice(device, _stream.Format); 
     } 

     public void Play() 
     { 
      _voice.SubmitSourceBuffer(_buffer); 
      _voice.Start(); 
     } 

     public void Dispose() 
     { 
      _stream.Close(); 
      _stream.Dispose(); 
      _buffer.Dispose(); 
      _voice.Dispose(); 
     } 
    } 

上面的代碼實際上是基於SlimDX樣品。

它現在是什麼,當我打電話播放()反反覆覆,播放聲音,如:

聲音 - >聲音 - >聲音

所以它只是填充緩衝和戲劇它。

但是,我需要能夠播放相同的聲音而當前播放的是,所以有效這兩個或兩個以上應該同時混合播放。

有沒有什麼我在這裏,我錯過了,或者這是不可能與我目前的解決方案(也許SubmixVoices可以幫助)?

我正在嘗試查找文檔中的相關內容,但我沒有成功,並且網上沒有很多示例可供參考。

謝謝。

回答

3

儘管爲了這個目的使用XACT是更好的選擇,因爲它支持聲音提示(正是我所需要的),我確實設法使它以這種方式工作。

我已經更改了代碼,所以它始終會從流中創建新的SourceVoice對象並播放它。

 // ------ code piece 

     /// <summary> 
     /// Gets the available voice. 
     /// </summary> 
     /// <returns>New SourceVoice object is always returned. </returns> 
     private SourceVoice GetAvailableVoice() 
     { 
      return new SourceVoice(_player.GetDevice(), _stream.Format); 
     } 

     /// <summary> 
     /// Plays this sound asynchronously. 
     /// </summary> 
     public void Play() 
     { 
      // get the next available voice 
      var voice = GetAvailableVoice(); 
      if (voice != null) 
      { 
       // submit new buffer and start playing. 
       voice.FlushSourceBuffers(); 
       voice.SubmitSourceBuffer(_buffer); 

       voice.Start(); 
      } 
     }