我有这个Webservice方法,用于从数据库中获取音频。服务器端:
[WebMethod]
public void PlayAudio(int id)
{
byte[] bytes = new byte[0];
using (The_FactoryDBContext db = new The_FactoryDBContext())
{
if (db.Words.FirstOrDefault(word => word.wordID == id).engAudio != null)
{
bytes = db.Words.FirstOrDefault(word => word.wordID == id).engAudio;
MemoryStream ms = new MemoryStream(bytes);
Context.Response.Clear();
Context.Response.AddHeader("ContentType ", "audio/wav");
Context.Response.BinaryWrite(ms.ToArray());
Context.Response.Flush();
Context.Response.Close();
}
}
}
我有这段代码在浏览器中播放此音频:
var audio = document.createElement('audio');
audio.id = "test";
audio.autoplay = false;
audio.preload = true;
audio.oncanplaythrough = function () {
foo.disabled = false;
};
var id = $("[id$=hiddenWord_id]").val();
audio.src =// below are the different ways ive tried
foo.onclick = function () {
audio.play();
}
我试过这个:
audio.src = "../../WebService.asmx/PlayAudio/?id=" + id;
这是为了到达webservie
document.getElementById('test').src = PlayAudio();
function PlayAudio() {
var id = $("[id$=hiddenWord_id]").val();
$.ajax({
url: "../../WebService.asmx/PlayAudio",
data: "{ 'id': '" + id + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
};
然而,上述情况似乎都不起作用。
答案 0 :(得分:1)
将其改写为ASHX。包括以下类(自己添加命名空间和使用语句,将文件命名为AudioHandler.ashx.cs):
public class AudioHandler : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
int id = Convert.ToInt32(context.Request.QueryString["id"]);
byte[] bytes = new byte[0];
using (The_FactoryDBContext db = new The_FactoryDBContext())
{
if (db.Words.FirstOrDefault(word => word.wordID == id).engAudio != null)
{
bytes = db.Words.FirstOrDefault(word => word.wordID == id).engAudio;
context.Response.ContentType = "audio/wav";
context.Response.BinaryWrite(bytes);
context.Response.Flush();
}
}
}
}
根据您的.NET版本,通过在web.config中指定处理程序或在站点的根目录中添加audiohandler.ashx文件来添加处理程序。将以下内容粘贴在其中:
<%@ WebHandler Language="C#" Class="AudioHandler" %>
现在您可以通过
调用该服务audio.src = "/AudioHandler.ashx?id=" + id;
您可以扩展ASHX文件以使其更加健壮(如果没有ID或者例如它不是有效整数,那该怎么办)