按键时使用NAudio播放MP3的高内存使用率 [英] High Memory Usage playing MP3's with NAudio on Key Press
问题描述
我正在使用C#,WPF和 NAudio .
I'm using C#, WPF, and NAudio.
按下键时,我在应用程序exe
中播放embedded
资源mp3
.
I play an embedded
resource mp3
in the application exe
when a key is pressed.
如果反复按某个键,则RAM的使用量将继续攀升至400MB以上,并且永不下降.
If a key is pressed repeatedly, RAM usage continues to climb past 400MB and never drops.
即使调用GC
,在对象上使用Flush()
和Dispose()
似乎也没有释放内存.
Using Flush()
and Dispose()
on the objects doesn't seem to free memory even when GC
is called.
当我使用string
路径而不是MemoryStream
从硬盘驱动器上的external
资源播放时,这种情况以前从未发生过.它曾经保持大约50MB的RAM.
This did not used to happen when I played from external
resource on the hard drive using string
path instead of MemoryStream
. It used to stay around 50MB RAM.
public static MemoryStream ms = null;
public static WaveStream wav = null;
public static WaveOutEvent output = null;
// Embedded Resource sound1.mp3
MemoryStream sound1 = new MemoryStream(Properties.Resources.sound1);
// Key Press
//
if (e.Key == Key.Space) {
ms = new MemoryStream(StreamToBytes(sound1));
wav = new Mp3FileReader(ms);
output = new WaveOutEvent();
output.PlaybackStopped += new EventHandler<StoppedEventArgs>(Media_Ended);
output.Init(wav);
output.Play();
}
// MP3 Playback Ended
//
public static void Media_Ended(object sender, EventArgs e)
{
if (output.PlaybackState == PlaybackState.Stopped)
{
ms.Flush();
ms = null;
wav.Close();
output.Dispose();
}
}
// Convert Stream to Byte Array
//
public static byte[] StreamToBytes(MemoryStream stream)
{
...
}
流到字节数组
https://stackoverflow.com/a/1080445/6806643
Stream to Byte Array
https://stackoverflow.com/a/1080445/6806643
我将字节数组转换回新的流,否则如果同时播放2个声音,则播放不会分层并且会崩溃.
I convert to Byte Array back to a new Stream or the playback will not layer and will crash if 2 sounds play at once.
推荐答案
这是因为单击空格键的速度太快了:)
It's because you clicking space bar too fast :)
每次击键都会用新值覆盖变量.因此,当您在几秒钟内单击空格键10次时,它将创建10个资源.但是,您仅引用创建的最后一个.当Media_Ended开始传入时,它将尝试仅处置最新创建的资源.
Each key click overwrites variables with new values. So when you click space bar 10 times in few seconds it will create 10 resources. But you keep reference to only last one created. When Media_Ended will start incoming, it will try to dispose only latest created resource.
这篇关于按键时使用NAudio播放MP3的高内存使用率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!