C# SoundPlayer static after WAV plays
-
12-12-2019 - |
Question
I'm using this code to play a WAV file from a resource, and the audio plays correctly, but then I get a short blast of static after it plays (about 1/2 second):
//System.Media.SystemSounds.Beep.Play();
SoundPlayer sndPlayer = new SoundPlayer();
sndPlayer.Stream = Resources.Notify;
sndPlayer.Play();
If I uncomment the System.Media.SystemSounds.Beep.Play()
line above, then the beep and the Notify sound from my resources both play correctly, and no static. I've tried a few different variations of the above code, and always getting the static. I tried making all of the variables static, incase there was something related to early garbage collection, but that didn't help.
The WAV file is just one I copied from c:\WINDOWS\Media\ding.wav
(on Windows XP) and it plays fine in Windows Media Player. Also, if I use new SoundPlayer("c:\WINDOWS\Media\ding.wav")
, it plays correctly from the file.
I imagine it has something to do with the UnmanagedMemoryStream
that Resources.Notify
is, and maybe I need to load it in to a managed stream first? I know I've had issues with PNG files if I don't use new Bitmap(Resource.MyPNG)
and try to use Resource.MyPNG
directly instead, so maybe something similar with WAV resources?
Update : I originally thought it was happening everytime the sound played, but now it appears it only happens the very first time I play the sound in my app. So maybe some initialization needs to be done?
I also tried this, same issue:
SoundPlayer sndPlayer = new SoundPlayer(Resources.Notify);
sndPlayer.Play();
Solution 2
Was just an issue on one PC. Never figured it out, and other apps don't appear to have this issue, but not worth my time if only on 1 PC (out of maybe 15 tested) so far. Will report a better answer if I ever get one.
OTHER TIPS
This is the internal implementation that MS use My.Audio.Play(), see how they instantiate the SoundPlayer class, they take advantage of the overloaded constructor that takes a filePath as shown below or a stream:
http://msdn.microsoft.com/en-us/library/system.media.soundplayer.aspx
public void Play(string location, AudioPlayMode playMode)
{
this.ValidateAudioPlayModeEnum(playMode, "playMode");
SoundPlayer sound = new SoundPlayer(this.ValidateFilename(location));
this.Play(sound, playMode);
}
Can you try passing in a stream when instantiating the SoundPlayer?