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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-10 12:21:26

问题


I'm using C#, WPF, and NAudio.

I play an embedded resource mp3 in the application exe when a key is pressed.

If a key is pressed repeatedly, RAM usage continues to climb past 400MB and never drops.

Using Flush() and Dispose() on the objects doesn't seem to free memory even when GC is called.

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)
{
    ...
}

Stream to Byte Array
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.


回答1:


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. But you keep reference to only last one created. When Media_Ended will start incoming, it will try to dispose only latest created resource.



来源:https://stackoverflow.com/questions/49186932/high-memory-usage-playing-mp3s-with-naudio-on-key-press

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!