Stream audio to a webpage from c#

2019-06-03 01:07发布

[WebMethod]
public void PlayAudio(int id)
{


    using (The_FactoryDBContext db = new The_FactoryDBContext())
    {
        if (db.Words.FirstOrDefault(word => word.wordID == id).engAudio != null)
        {
            byte[] bytes = db.Words.FirstOrDefault(word => word.wordID == id).engAudio;

            MemoryStream ms = new MemoryStream(bytes);
            System.Media.SoundPlayer myPlayer = new System.Media.SoundPlayer(ms);
            myPlayer.Play();
        }
    }



}

Apparently in the code above what actually plays the audio is the C# code through the System.Media.SoundPlayer object and not the browser which is why it won't play on a server.

Can anyone show me how to stream audio to a webpage from c# so I can hook it to a button using HTML5 audio tags

1条回答
唯我独甜
2楼-- · 2019-06-03 01:33

Just send the stream to the client, and the browser will decide how to play it(You must provide the MIME type for audio):

public ActionResult PlayAudio(int id)
{
    MemoryStream ms = null;
    using (The_FactoryDBContext db = new The_FactoryDBContext())
    {
        if (db.Words.FirstOrDefault(word => word.wordID == id).engAudio != null)
        {
            byte[] bytes = db.Words.FirstOrDefault(word => word.wordID == id).engAudio;

            ms = new MemoryStream(bytes);
        }
    }
    return File(ms,"audio/mpeg");//if it's mp3
}

For web service, try this:

[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;

        }
    }
    Context.Response.Clear();
    Context.Response.ClearHeaders();
    Context.Response.ContentType = "audio/mpeg";
    Context.Response.AddHeader("Content-Length", bytes.Length.ToString());
    Context.Response.OutputStream.Write(bytes, 0, bytes.Length);
    Context.Response.End();
}
查看更多
登录 后发表回答