我尝试使用 PushStreamContent 和 WebApi 流式传输音频。为此,我编写了一些代码。主要代码;
[HttpGet]
public HttpResponseMessage StreamCall(long callId,int playSpeed)
{
var audio = new AudioStreamHelper();
var response = Request.CreateResponse();
response.Content = new PushStreamContent((Action<Stream, HttpContent, TransportContext>) audio.WriteToStream, new MediaTypeHeaderValue("audio/wav"));
return response;
}
AudioStreamHelper 代码;
public class AudioStreamHelper
{
private readonly string _filename;
protected static readonly ILogger Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType.Name);
public AudioStreamHelper()
{
_filename = @"C:/195545.mp3";
}
public async void WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
{
try
{
var buffer = new byte[12365536];
using (var audio = File.Open(_filename, FileMode.Open, FileAccess.Read,FileShare.ReadWrite))
{
var length = (int)audio.Length;
var bytesRead = 1;
while (length > 0 && bytesRead > 0)
{
bytesRead = audio.Read(buffer, 0, Math.Min(length, buffer.Length));
await outputStream.WriteAsync(buffer, 0, bytesRead);
length -= bytesRead;
}
}
}
catch (HttpException ex)
{
Logger.Error(ex.Message);
throw new UserFriendlyException(AppTexts.AudioStreamError);
}
finally
{
outputStream.Close();
}
}
}
当我调试这段代码时;在 AudioStreamHelper 类 WriteToStream 方法和await outputStream.WriteAsync(buffer, 0, bytesRead);
行中,我的线程被锁定/冻结并且没有响应。我检查当前线程 ID。是一样的。(在 Api 和 Helper 类中)此外,此代码适用于 System.Net.Http.Formattion(版本 4.0.0.0)的另一个演示应用程序我的项目使用 System.Net.Http.Formattion(版本 5.1.0.0)关联有这个条件?我不明白这种情况。