声音播放导致内存泄漏? [英] SoundPlayer causing Memory Leaks?

查看:558
本文介绍了声音播放导致内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写在C#中的基本写作应用程序,我想有该程序使打字机的声音,你键入。我已经迷上了我的RichTextBox到使用的SoundPlayer每次关键是pressed打短WAV文件中的函数重点preSS事件,但是我以后发现,而我的计算机速度变慢到抓取和检查我的过程,audiodlg.exe使用5 GB的RAM。

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.

在code我使用如下:

The code I'm using is as follows:

我初始化SoundPlayer类作为程序的全局变量开始

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

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

然后在关键preSS事件中,我只需拨打

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.

推荐答案

不要使用声音播放 - 使用 waveout的... API来代替:

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

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

声音播放更像是一个玩具不是一个生产就绪的组成部分,但我敢肯定,写了MS实习生是好意。 :)

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

更新:如果您使用链接的样品和熟悉的code,你会看到有什么可能是错误的声音播放的实施。与 waveout的... 功能播放音频涉及两个内存缓冲区:一个小小的一个头,比包含实际样本数据的一个潜在大的缓冲区。您链接到的修补程序文章中提到几百个字节每次播放的泄漏被调用,这意味着code为每次大概实例化一个新的标题,然后不能正确处理它。 (这是假设声音播放包装了 waveout的... API - 我不知道这是否是这种情况或不)

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.

这篇关于声音播放导致内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆