我使用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);
如何通过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();
答案 0 :(得分:0)
我想出了如何让它发挥作用。
此解决方案的问题是内存使用率很高。
// 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();
// 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();
}
}
}