如何强制发送响应流

本文关键字:响应 何强制 | 更新日期: 2023-09-27 18:08:48

我正在发送响应流音频,有时文件大到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();
        }
    };
}

如何强制发送响应流

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