I have created a simple game for WinRT, and now I want to add sound when the user clicks the buttons.
How can I play the same sound many times? I'm using this code, but it's too slow - sometimes when I click the buttons too fast, the sound is not played.
The class is a Service of MVVM, but if you don't know how to use it, treat it as a static class.
public class SoundService : ISoundService
{
#region Variables
private SourceVoice VoicePlayer;
private AudioBuffer ClickBuffer;
uint[] packetInfo;
#endregion
#region Public Methods
public async void PlayClickSound()
{
InitializePlayers();
VoicePlayer.SubmitSourceBuffer(ClickBuffer, packetInfo);
VoicePlayer.Start();
}
#endregion
#region Private Methods
private void InitializePlayers()
{
if (this.playersInitialized)
return;
XAudio2 xaudio;
MasteringVoice masteringVoice;
xaudio = new XAudio2();
masteringVoice = new MasteringVoice(xaudio);
NativeFileStream nativefilestream = new NativeFileStream(
@"Data\Sounds\Click.wav",
NativeFileMode.Open,
NativeFileAccess.Read,
NativeFileShare.Read);
SoundStream soundstream = new SoundStream(nativefilestream);
WaveFormat waveFormat = soundstream.Format;
ClickBuffer = new AudioBuffer
{
Stream = soundstream.ToDataStream(),
AudioBytes = (int)soundstream.Length,
Flags = BufferFlags.EndOfStream
};
VoicePlayer = new SourceVoice(xaudio, waveFormat, true);
this.packetInfo = soundstream.DecodedPacketsInfo;
this.playersInitialized = true;
}
#endregion
#region Flags
bool playersInitialized = false;
#endregion
}
What shall I do? Please, help.