0

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!

OverMars
  • 1,077
  • 3
  • 16
  • 33

2 Answers2

1

I think this makes little difference, because either way it only needs to be instantiated only once - since you are playing the same file.

Declare a class member of type SoundPlayer, and instantiate it using initializer.

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

or

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

and whenever you need to play the sound, you don't need to perform null-check against it, just call

soundPlayer.Play(); 

For resource disposal, call Dispose method on the instance if you no longer use it, for example, when the window is closed.

soundPlayer.Dispose();
kennyzx
  • 12,845
  • 6
  • 39
  • 83
  • Both answers helped greatly, in not needing to perform null check (and mark as readonly from mm8. Ty both – OverMars Nov 02 '18 at 23:00
  • 2
    The accepted answer is a better one since it introduces the _readonly_ keyword to enforce that the constructor will not be called more than once. – kennyzx Nov 03 '18 at 00:39
1

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.

mm8
  • 163,881
  • 10
  • 57
  • 88