我正在尝试将音频文件流式传输到Angular应用程序,其中html5音频元素和src设置为我的api端点(例如/ audio / 234)。我的后端是通过.NET Core 2.0实现的。我已经实现了这种流式传输:.NET Core| MVC pass audio file to html5 player. Enable seeking
如果在音频开始播放时我不立即寻求文件结尾,则可以进行搜索。我使用音频元素的autoplay属性立即开始播放音频元素具有足够的数据。因此,在我的情况下,音频元素在我搜索时还没有所有数据,因此可以对我的API进行新的获取。在这种情况下,我的后端日志中会出现以下异常:
fail: Microsoft.AspNetCore.Server.Kestrel[13] [1] Connection id "0HL9V370HAF39", Request id "0HL9V370HAF39:00000001": An unhandled exception was thrown by the application. [1] System.InvalidOperationException: Response Content-Length mismatch: too few bytes written (0 of 6126919).
这是我的音频 Controller 的GET方法。
byte[] audioArray = new byte[0];
//Here I load audio file from cloud
long fSize = audioArray.Length;
long startbyte = 0;
long endbyte = fSize - 1;
int statusCode = 200;
var rangeRequest = Request.Headers["Range"].ToString();
_logger.LogWarning(rangeRequest);
if (rangeRequest != "")
{
string[] range = Request.Headers["Range"].ToString().Split(new char[] { '=', '-' });
startbyte = Convert.ToInt64(range[1]);
if (range.Length > 2 && range[2] != "") endbyte = Convert.ToInt64(range[2]);
if (startbyte != 0 || endbyte != fSize - 1 || range.Length > 2 && range[2] == "")
{ statusCode = 206; }
}
_logger.LogWarning(startbyte.ToString());
long desSize = endbyte - startbyte + 1;
_logger.LogWarning(desSize.ToString());
_logger.LogWarning(fSize.ToString());
Response.StatusCode = statusCode;
Response.ContentType = "audio/mp3";
Response.Headers.Add("Content-Accept", Response.ContentType);
Response.Headers.Add("Content-Length", desSize.ToString());
Response.Headers.Add("Content-Range", string.Format("bytes {0}-{1}/{2}", startbyte, endbyte, fSize));
Response.Headers.Add("Accept-Ranges", "bytes");
Response.Headers.Remove("Cache-Control");
var stream = new MemoryStream(audioArray, (int)startbyte, (int)desSize);
return new FileStreamResult(stream, Response.ContentType)
{
FileDownloadName = track.Name
};
我缺少标题吗?
我没有在.NET Core 1.1中遇到此异常,但是我不确定这只是巧合和/或不好的测试。但是,如果任何人都有信息,.NET Core中与流传输有关的内容都会发生变化,我将感激该信息。
最佳答案
现在,当我进行更多研究时,发现:https://docs.microsoft.com/en-us/aspnet/core/aspnetcore-2.0外观增强的HTTP header 支持标题。这样说
If an application visitor requests content with a Range Request header, ASP.NET will recognize that and handle that header. If the requested content can be partially delivered, ASP.NET will appropriately skip and return just the requested set of bytes. You do not need to write any special handlers into your methods to adapt or handle this feature; it is automatically handled for you.
因此,当我移至.NET Core 1.1到2.0时,我需要做的是清理工作,因为这些 header 已经有了处理程序。
byte[] audioArray = new byte[0];
//Here I get my MP3 file from cloud
var stream = new MemoryStream(audioArray);
return new FileStreamResult(stream, "audio/mp3")
{
FileDownloadName = track.Name
};
关于html - HTML5音频搜寻无法正常工作。引发响应内容长度不匹配异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47730373/