Stream audio to a webpage from c#

会有一股神秘感。 提交于 2019-12-08 05:16:06

问题


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


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();
}


来源:https://stackoverflow.com/questions/32258284/stream-audio-to-a-webpage-from-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!