从c#将音频流式传输到网页 [英] Stream audio to a webpage from c#

查看:202
本文介绍了从c#将音频流式传输到网页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



}

显然在上面的代码中实际播放音频的是通过System.Media.SoundPlayer对象的C#代码而不是浏览器,这就是它不能在服务器上播放的原因。

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.

任何人都可以告诉我如何从c#将音频流式传输到网页,这样我就可以使用HTML5音频标签将其挂钩到按钮

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

推荐答案

只需将流发送到客户端,浏览器就会决定如何播放它(你必须提供音频的MIME类型):

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

这篇关于从c#将音频流式传输到网页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆