How to stream an mp3 file from a URL without using

2019-09-14 21:14发布

问题:

I have a method to stream mp3 from url sources. In this method, the file begins downloading and at the same time the downloaded bytes are stored in a MemoryStream. But I realized that this method is not good. Because the RAM usage is approximately 50 mb when the mp3 file is being played.

So I want to make it without storing in MemoryStream. I tried storing the downloaded bytes in a temporary file, but it didn't worked. How to fix it to work with FileStream?

It works good using MemoryStream:

MemoryStream ms = new MemoryStream();
int bytesRead = 0;
long pos = 0;
int total = 0;

do
{
   bytesRead = responseStream.Read(buffer, 0, buffer.Length);
   Buffer.BlockCopy(buffer, 0, bigBuffer, total, bytesRead);
   total += bytesRead;
   pos = ms.Position;
   ms = new MemoryStream(bigBuffer);
   ms.Position = pos;
   frame = Mp3Frame.LoadFromStream(ms);

   //Other codes to play mp3...
}
while (bytesRead > 0 || waveOut.PlaybackState == PlaybackState.Playing);

This code throws exception on the LoadFromStream line with FileStream

int bytesRead = 0;
long pos = 0;
int total = 0;
string path =Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),"temp.mp3");
FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
do
{
   bytesRead = responseStream.Read(buffer, 0, buffer.Length);
   total += bytesRead;
   pos = fs.Position;
   fs.Write(buffer, 0, bytesRead);
   fs.Position = pos;
   frame = Mp3Frame.LoadFromStream(fs);

   //Other codes to play mp3...
}
while (bytesRead > 0 || waveOut.PlaybackState == PlaybackState.Playing);