C# WPF SoundPlayer

[link to code file]

When you want a lite weight sound object in WPF, the SoundPlayer object is the thing to use.

Its got a very small API.

For most applications, all you need to do is create an instance with a string to the wav file that you want to load and then call the Play() function

example

SoundPlayer sp = new SoundPlayer(@"c:\temp\mysound.wav");
sp.Play();

SoundPlayer goes off and loads the wav file and the plays the wav file in a background thread, like it should.

Thats great unless I want it associated with a remote control button press

My first run at SoundPlayer left me with a less than optimum user experience. I wanted to play a sound when I handled a button press on the Microsoft Media Center remote control.

If the user holds down a remote control button, then under Windows XP, it makes the sound, then intermittently makes the sound from then on. Not too bad a result.

Under Vista, its a different story. Vista starts to play the sound, then blocks it and tries to play the sound again. The result is a "stutter" from the wav file being played over and over again. Even worse, it queues up so that the stutter continues long after the remote button is released.

Welcome to the extended SoundPlayer

Extended SoundPlayer. Is a simple derived class based on SoundPlayer. The big change is that it doesn't try to play another sound if it is already playing a sound. The other functionality it gives is that you can check if the sound is playing from your own code.

Feel free to use Extended Sound Player for your own projects. It is provided without any support or warranty. The blogging editor removes the Tabs from the code, so you'll have to reformat the code.

using System;
using System.Collections.Generic;
using System.Text;

using System.Media;

using System.Threading;

using System.Windows.Threading;

namespace ExtendedSoundPlayer
{
class CExtendedSoundPlayer : SoundPlayer
{
private bool myBoolIsplaying = false;

public bool bIsPlaying
{

get { return myBoolIsplaying; }

}


public CExtendedSoundPlayer(String strFilename) : base(strFilename) { }

public void PlaySound()
{
if (!bIsPlaying)
{
Thread threadSound = new Thread(new ThreadStart(PlaySoundThread));
threadSound.Start();

}


}


protected virtual void PlaySoundThread()
{

myBoolIsplaying = true;


//PlaySync plays the sound in the same thread and doesn't return till it is finished.
PlaySync();

myBoolIsplaying = false;
}

}
}

More ways to skins a cat

C# also includes the SoundPlayerAction class which allows you to connect up the sound player to specific events in WPF.



0 comments: