简体   繁体   English

高内存使用率在按键时使用 NAudio 播放 MP3

[英]High Memory Usage playing MP3's with NAudio on Key Press

I'm using C#, WPF, and NAudio .我正在使用 C#、WPF 和NAudio

I play an embedded resource mp3 in the application exe when a key is pressed.当按下某个键时,我会在应用程序exe播放embedded资源mp3

If a key is pressed repeatedly, RAM usage continues to climb past 400MB and never drops.如果重复按下某个键,RAM 使用量会继续攀升超过 400MB,并且永远不会下降。

Using Flush() and Dispose() on the objects doesn't seem to free memory even when GC is called.即使在调用GC时,对对象使用Flush()Dispose()似乎也不会释放内存。

This did not used to happen when I played from external resource on the hard drive using string path instead of MemoryStream .当我使用string路径而不是MemoryStream从硬盘驱动器上的external资源播放时,这并没有发生。 It used to stay around 50MB RAM.它曾经保持在 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)
{
    ...
}

Stream to Byte Array流到字节数组
https://stackoverflow.com/a/1080445/6806643 https://stackoverflow.com/a/1080445/6806643

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.我将字节数组转换回新的流,否则如果同时播放 2 个声音,播放将不会分层并且会崩溃。

It's because you clicking space bar too fast :)那是因为你点击空格键太快了:)

Each key click overwrites variables with new values.每次按键都会用新值覆盖变量。 So when you click space bar 10 times in few seconds it will create 10 resources.因此,当您在几秒钟内单击空格键 10 次时,它将创建 10 个资源。 But you keep reference to only last one created.但是你只引用最后一个创建的。 When Media_Ended will start incoming, it will try to dispose only latest created resource.当 Media_Ended 开始传入时,它将尝试仅处理最新创建的资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM