Skip to content

Instantly share code, notes, and snippets.

@Cameron-D
Created July 15, 2011 13:49
Show Gist options
  • Save Cameron-D/1084727 to your computer and use it in GitHub Desktop.
Save Cameron-D/1084727 to your computer and use it in GitHub Desktop.
class publicSound {
private System.ComponentModel.BackgroundWorker backgroundWorker;
private XAudio2 device; //declare it here so we don't need it as a parmeter later
private MasteringVoice masteringVoice;
private bool shouldPlay;
public publicSound() {
device = new XAudio2();
masteringVoice = new MasteringVoice(device);
shouldPlay = true;
backgroundWorker = new System.ComponentModel.BackgroundWorker();
this.backgroundWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker_DoWork);
}
public void PlaySound(string fileName) {
backgroundWorker.RunWorkerAsync(fileName);
}
public void CleanUp() {
shouldPlay = false; //stop all playing sounds
Thread.Sleep(10); //wait for them to stop
device.Dispose();
masteringVoice.Dispose();
}
private void backgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) {
string fileName = (string)e.Argument;
var s = System.IO.File.OpenRead(fileName);
WaveStream stream = new WaveStream(s);
s.Close();
AudioBuffer buffer = new AudioBuffer();
buffer.AudioData = stream;
buffer.AudioBytes = (int)stream.Length;
buffer.Flags = BufferFlags.EndOfStream;
SourceVoice sourceVoice = new SourceVoice(device, stream.Format);
sourceVoice.SubmitSourceBuffer(buffer);
sourceVoice.Start();
while (sourceVoice.State.BuffersQueued > 0)
{
if (!shouldplay) //should we be shutting down?
break;
Thread.Sleep(10);
}
buffer.Dispose();
sourceVoice.Dispose();
stream.Dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment