2015-08-27 115 views
1
[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#代碼,而不是瀏覽器這就是爲什麼它不會在服務器上玩。流音頻到網頁從C#

誰能告訴我如何流音頻從C#中的網頁這樣我就可以使用HTML5音頻標籤

+1

看看這個:http://www.w3schools.com/html/html5_audio .asp,你正在執行代碼在服務器端,只需添加一個Audio標籤並將其指向您的aspx,那麼aspx應該像Taher所說的那樣返回該流。 – Gusman

+0

請看看這個:https://developer.mozilla.org/en/docs/Web/HTML/Element/audio – rlemon

回答

2

只發送數據流給客戶其掛到一個按鈕,瀏覽器將決定如何玩(您必須提供的MIME類型音頻):

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 
} 

對於web服務,試試這個:

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

您正在使用上述代碼中的控制器,在那裏我使用webservice來調用音頻在數據庫中。我會更新我的問題來說明。 –

+0

當前上下文中不存在名稱'Response' –

+0

使用'Context.Response',我改變了答案 –