我有一种从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);