我每秒播放5次相同的声音文件(在它们之间随机选择),而且我总是加载到内存中,因此该程序占用大量内存。如何将声音文件加载到内存中,然后从那里启动?我正在使用NAudio。当前代码:

var sound = "sounds/test.mp3";
using (var audioFile = new AudioFileReader(sound))
using (var outputDevice = new WaveOutEvent())
{
    outputDevice.Init(audioFile);
    outputDevice.Play();
    while (outputDevice.PlaybackState == PlaybackState.Playing)
    {
        Thread.Sleep(1000);
    }
    threadStop();
}

最佳答案

如果删除using块,则不会处理audioFileoutputDevice。然后,您可以将它们保留在内存中,并且每次播放音频时都将使用相同的引用。

使用using块,您将重复实例化其内存可能不会立即释放的NAudio对象。

var sound = "sounds/test.mp3";
var audioFile = new AudioFileReader(sound);
var outputDevice = new WaveOutEvent();
outputDevice.Init(audioFile);
outputDevice.Play();
while (outputDevice.PlaybackState == PlaybackState.Playing)
{
    Thread.Sleep(1000);
}
threadStop();

关于c# - 如何使用NAudio将声音文件加载到内存中并在以后使用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50241298/

10-13 07:01