【发布时间】:2018-12-21 04:27:03
【问题描述】:
我在一个项目中使用 ASP.NET MVC 和 C#。
一个任务是:当用户点击一个链接时,需要从链接中获取id,然后使用这个链接生成一个外部链接,这是一个音频文件,然后在网络浏览器中播放(不另存为文件)。
目前的解决方案是:从外部链接下载音频文件,获取字节,然后将其作为音频/wav放入响应中
public async Task<HttpResponseMessage> StreamAudioAsync(string id)
{
var response = Request.CreateResponse(HttpStatusCode.Moved);
var data = GetAudio(id);
if (data != null && data.Length > 0)
{
response.StatusCode = HttpStatusCode.OK;
response.Content = new ByteArrayContent(data);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("audio/wav");
}
return response;
}
private byte[] GetAudio(string id)
{
string accessKey = Cp.Service.Settings.AccessKey;
string secretAccessKey = Cp.Service.Settings.SecretAccessKey;
string url = string.Format("https://....../......php?access_key={0}&secret_access_key={1}&action=recording.download&format=mp3&sid={2}", accessKey, secretAccessKey, id);
byte[] data = null;
try
{
using (var wc = new System.Net.WebClient())
{
data = wc.DownloadData(url);
}
}
catch //(Exception ex)
{
//forbidden, proxy issues, file not found (404) etc
//ms = null;
}
return data;
}
这将首先下载音频数据。有没有办法将音频流从 url 直接流式传输到响应?这样,服务器不会在内存中保存数据bytes[]?有时,数据量很大。
谢谢
【问题讨论】:
标签: c# asp.net-mvc