如何使用NAudio从Embedded Resources播放WAV文件?

时间:2018-03-08 16:38:30

标签: c# naudio

我使用C#,WPF和NAudio播放wav文件。

我在Resources文件夹中有sound_1.wav并包含在项目中。编译完成后,它会将exe和资源导出到文件夹,然后从硬盘驱动器上的路径播放wav。

string sound1 = "Resources\\sound_1.wav";

NAudio.Wave.WaveFileReader wav = new NAudio.Wave.WaveFileReader(sound1);
WaveOutEvent output = new WaveOutEvent();
output.Init(wav);
output.Play();

但我想将wav文件嵌入exe并使用类似的内容:

UnmanagedMemoryStream sound1 = Properties.Resources.sound_1; //embedded resource
NAudio.Wave.WaveFileReader wav = new NAudio.Wave.WaveFileReader(sound1);

Embedded Resources

如何通过WaveFileReader播放?它只接受string路径。

解决方案

这样可行,但声音以慢动作播放,听起来像混响。

UnmanagedMemoryStream sound1 = Properties.Resources.sound_1;

WaveIn wavin = new WaveIn();
NAudio.Wave.RawSourceWaveStream wav = new NAudio.Wave.RawSourceWaveStream(sound1, wavin.WaveFormat);         
WaveOutEvent output = new WaveOutEvent();
output.Init(wav);
output.Play();

这在声音结束时会发出响亮的声音。

将流转换为字节数组
https://stackoverflow.com/a/1080445/6806643

byte[] b = ReadToEnd(sound1);

WaveStream wav = new RawSourceWaveStream(new MemoryStream(b), new WaveFormat(44100, 16, 2));
WaveOutEvent output = new WaveOutEvent();
output.Init(wav);
output.Play();

1 个答案:

答案 0 :(得分:0)

我想出了如何让它发挥作用。

此解决方案的问题是内存使用率很高。

WAV

// embedded resource sound.wav

UnmanagedMemoryStream sound = Properties.Resources.sound;

MemoryStream ms = new MemoryStream(StreamToBytes(sound));

WaveStream ws = new WaveFileReader(ms);

WaveOutEvent output = new WaveOutEvent();

output.PlaybackStopped += new EventHandler<StoppedEventArgs>(Media_Ended);
output.Init(ws);
output.Play();

MP3

// embedded resource sound.mp3

MemoryStream sound = new MemoryStream(Properties.Resources.sound);

MemoryStream ms = new MemoryStream(StreamToBytes(sound));

WaveStream ws = new Mp3FileReader(ms);

WaveOutEvent output = new WaveOutEvent();

output.PlaybackStopped += new EventHandler<StoppedEventArgs>(Media_Ended);
output.Init(ws);
output.Play();

流到字节数组

https://stackoverflow.com/a/1080445/6806643

我用它来将MemoryStream转换为byte[],否则如果2个声音与Exception "Not a WAVE file - no RIFF header"同时播放,它就会崩溃。

处置

似乎对减少RAM没有任何影响。

public static void Media_Ended(object sender, EventArgs e)
{
    if (output.PlaybackState == PlaybackState.Stopped)
    {
        if (ms != null)
        {
            ms.Close();
            ms.Flush();
        }
        if (ws != null)
        {
            ws.Close();
        }
        if (output != null)
        {
            output.Dispose();
        }
    }
}