Save streaming data to a WAV file using NAudio

江枫思渺然 提交于 2019-12-06 06:09:01
MattW

I wouldn't take that particular approach to saving to disk. It's a bit too hands-on, because it has to deal with playing back at the right rate. Just buffer up the response, and then wrap it in an Mp3FileReader stream and use WaveFileWriter to write the WAV file:

MemoryStream mp3Buffered = new MemoryStream();
using (var responseStream = resp.GetResponseStream())
{
    byte[] buffer = new byte[65536];
    int bytesRead = responseStream.Read(buffer, 0, buffer.Length);
    while (bytesRead > 0)
    {
        mp3Buffered.Write(buffer, 0, bytesRead);
        bytesRead = responseStream.Read(buffer, 0, buffer.Length);
    }
}

mp3Buffered.Position = 0;
using (var mp3Stream = new Mp3FileReader(mp3Buffered))
{    
    WaveFileWriter.CreateWaveFile("file.wav", mp3Stream);
}

That does, of course, assume that your MP3 file's wave format is compatible with WAV and in particular, your WAV player. If it isn't, you'll need to inject and add a WaveFormatConversion stream as well.

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