简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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