How to stream an mp3 file from a URL without using much RAM?

拜拜、爱过 提交于 2020-01-25 21:51:13

问题


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);

来源:https://stackoverflow.com/questions/39544929/how-to-stream-an-mp3-file-from-a-url-without-using-much-ram

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