我尝试使用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)
与这种情况有关吗?我不明白这种情况。