Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SoundPlayer causing Memory Leaks?

I'm writing a basic writing app in C# and I wanted to have the program make typewriter sounds as you typed. I've hooked the KeyPress event on my RichTextBox to a function that uses a SoundPlayer to play a short wav file every time a key is pressed, however I've noticed after a while my computer slows to a crawl and checking my processes, audiodlg.exe was using 5 GIGABYTES of RAM.

The code I'm using is as follows:

I initialise the SoundPlayer as a global variable on program start with

SoundPlayer sp = new SoundPlayer("typewriter.wav")

Then on the KeyPress event I simply call

sp.Play();

Does anybody know what's causing the heavy memory usage? The file is less than a second long, so it shouldn't be clogging the thing up too much.

like image 358
Nick Udell Avatar asked Nov 05 '10 16:11

Nick Udell


2 Answers

Don't use SoundPlayer - use the waveOut... API instead:

http://www.codeproject.com/Articles/4889/A-full-duplex-audio-player-in-C-using-the-waveIn-w

SoundPlayer is more like a toy than a production-ready component, although I'm sure the MS intern that wrote it meant well. :)

Update: if you use the linked sample and get familiar with the code, you'll see what's probably wrong with the SoundPlayer implementation. Playing audio with the waveOut... functions involves two in-memory buffers: one small one for the header, and one potentially large buffer than contains the actual sample data. The hotfix article you linked to mentions the leak of a few hundred bytes each time Play is called, which means the code is probably instantiating a new header each time and then not disposing of it properly. (This is assuming SoundPlayer wraps the waveOut... API - I don't know whether this is the case or not)

Programmers take for granted the maxim "don't reinvent the wheel". Well, sometimes the wheel desperately needs reinventing.

like image 158
MusiGenesis Avatar answered Nov 16 '22 09:11

MusiGenesis


It could be a bug in the SoundPlayer.

Try this article on code project, maybe it will give you some hints.

like image 22
Liviu Mandras Avatar answered Nov 16 '22 09:11

Liviu Mandras