如何在不使用大量RAM的情况下从URL流式传输mp3文件?

时间:2016-09-17 09:02:05

标签: c# streaming filestream naudio memorystream

我有一种从url源流式传输mp3的方法。在此方法中,文件开始下载,同时下载的字节存储在MemoryStream中。但我意识到这种方法并不好。因为播放mp3文件时RAM的使用量约为50 MB。

所以我想在没有存储在MemoryStream中的情况下制作它。我尝试将下载的字节存储在一个临时文件中,但它没有用。如何修复它以使用FileStream?

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

此代码使用FileStream

在LoadFromStream行上抛出异常
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);

0 个答案:

没有答案