我发送响应流音频,有时文件大小为2gb因此我无法发送整个文件。我寄了1mb的块。
当播放音频并达到播放1mb的点时,它会寻找下一个1mb,从而在播放时产生微滞后,因为它等待下一个兆字节加载。
因此,我的问题是,即使在请求之前,我怎么能强制发送下一兆字节?它甚至可能吗?
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
// Default positions
var startPosition = 0;
var endPosition = 1048576; // 1mb
var rangeString = Request.Headers["Range"].FirstOrDefault();
var totalLength = fs.Length;
// Get positions
if (rangeString != null)
{
var rangeHeaders = rangeString.Split(new[] { '=', '-' });
startPosition = Convert.ToInt32(rangeHeaders[1]);
if (rangeHeaders.Length > 2 && !string.IsNullOrEmpty(rangeHeaders[2]))
{
endPosition = Convert.ToInt32(rangeHeaders[2]);
}
else
{
endPosition = startPosition + 1048576;
}
}
// Read bytes and slice 1mb
var takeHowMuch = endPosition - startPosition;
var outputBytes = new byte[takeHowMuch];
using (var reader = new BinaryReader(fs))
{
reader.BaseStream.Seek(startPosition, SeekOrigin.Begin);
reader.Read(outputBytes, 0, endPosition - startPosition);
}
return new Response
{
StatusCode = HttpStatusCode.PartialContent,
ContentType = "audio/mp3",
Headers =
{
new KeyValuePair<string, string>("Accept-Ranges", "bytes"),
new KeyValuePair<string, string>("Content-Range", string.Format("bytes {0}-{1}/{2}", startPosition, endPosition , totalLength)),
new KeyValuePair<string, string>("Content-Length", outputBytes.Length.ToString(CultureInfo.InvariantCulture))
},
Contents = s =>
{
s.Write(outputBytes, 0, takeHowMuch);
s.Flush();
}
};
}
答案 0 :(得分:0)
return new Response
{
StatusCode = HttpStatusCode.PartialContent,
ContentType = "audio/mp3",
Headers =
{
new KeyValuePair<string, string>("Accept-Ranges", "bytes"),
new KeyValuePair<string, string>("Content-Range", string.Format("bytes {0}-{1}/{2}", startPosition, endPosition , totalLength)),
new KeyValuePair<string, string>("Content-Length", outputBytes.Length.ToString(CultureInfo.InvariantCulture))
},
Contents = s =>
{
// I can write here multiple times thus sending multiple chunks
s.Write(outputBytes, 0, takeHowMuch);
s.Write(otherOutputBytes, 0, takeHowMuch);
}
};