tmighty
tmighty

Reputation: 11419

Saving MemoryStream to File produces 0 bytes

I'm using this code to write an MP3 MemoryStream to file:

using (var nSpeakStreamAsMp3 = new MemoryStream())
using (var nWavFileReader = new WaveFileReader(nSpeakStream))
using (var nMp3Writer = new LameMP3FileWriter(nSpeakStreamAsMp3, nWavFileReader.WaveFormat, LAMEPreset.STANDARD_FAST))
{
    nWavFileReader.CopyTo(nMp3Writer);

    string sPath = "C:\\inetpub\\wwwroot\\server\\bin\\mymp3.mp3";

    using (FileStream nFile = new FileStream(sPath, FileMode.Create, System.IO.FileAccess.Write))
    {
        nSpeakStreamAsMp3.CopyTo(nFile);
    }

    sRet = (String.Concat("data:audio/mpeg;base64,", Convert.ToBase64String(nSpeakStreamAsMp3.ToArray())));
}

return sRet;

For some reason which I don't see, this produces a file of 0 bytes. However, the MP3 stream is valid and does work. I'm passing it as a Base64String to a website, and I do hear it.

Where might be the error here?

Upvotes: 0

Views: 2419

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064114

  1. nSpeakStreamAsMp3 is currently positioned at the end of the stream; you need to think like a VCR: be kind, rewind (nSpeakStreamAsMp3.Position = 0;) before you copy the value out again
  2. make sure you flush nMp3Writer; if possible, close nMp3Writer completely

Upvotes: 5

Related Questions