Search code examples
c#wpfstaticinstance-variablessoundplayer

C# SoundPlayer - should be static or instance based?


I am using SoundPlayer class in C# (WPF), to play the same .5s audio over and over (on key press). Every time user presses custom on-screen keyboard buttons, sound plays.

static SoundPlayer soundPlayer = null;
try
{
  soundPlayer = new SoundPlayer(@"c:\media\click.wav");
}
catch (Exception e)
{
  Logger.LogException(e);
}
// later on (usage)    
try
{
  soundPlayer?.Play();
}

Can anyone provide some guidance on if I should keep this SoundPlayer obj as static or if I should change to instance based? Thanks!


Solution

  • Can anyone provide some guidance on if I should keep this SoundPlayer obj as static or if I should change to instance based?

    It depends on where and how the SoundPlayer is intended to be used in your application. If you will/can always use same instance of the SoundPlayer without modifying it in any way, you could define it as a static and readonly field in your class:

    private static readonly SoundPlayer soundPlayer = new SoundPlayer(@"c:\media\click.wav");
    

    Then there will only be one instance created regardless of the number of runtime instances of your class. The Play() method will play the .wav file using a new thread.