2015-07-06 23 views
9

Tôi có bài hát của tôi được lưu trữ trong cơ sở dữ liệu như byte []. Làm cách nào để sử dụng chúng trong thẻ <audio>.MVC điều khiển âm thanh chơi bài hát từ byte

Vì vậy, một cái gì đó như thế này. Tôi có cần phải chuyển đổi các byte thành cái gì khác trước không? Tôi không chắc.

foreach (var item in Model) 
    { 
     <audio controls> 
      <source [email protected] type="audio/mp3"/> 
     </audio> 
    } 

Trả lời

10

Một cách sẽ có thêm một hành động mới trong điều khiển của bạn mà trả về dữ liệu:

public ActionResult Audio(int someId) 
{ 
    byte[] songBytes; 
    // Add code to get data 
    return new FileStreamResult(songBytes, "audio/mp3"); 
} 

Sau đó đưa URL đó vào thuộc tính src:

foreach (var item in Model) 
{ 
    <audio controls> 
     <source src="/Controller/Audio/@item.someId" type="audio/mp3"/> 
    </audio> 
} 
0

Google chrome/Ipad yêu cầu hỗ trợ cho các yêu cầu nội dung tầm xa, vì vậy để thêm vào câu trả lời đưa ra ở đây, làm một cái gì đó như thế này:

public FileStreamResult StreamUploadedSongs(int id) 
    { 
     byte[] song = db.UploadedSongs.Where(x => x.Id == id).FirstOrDefault().SongBytes; 

     long fSize = song.Length; 
     long startbyte = 0; 
     long endbyte = fSize - 1; 
     int statusCode = 200; 
     if ((Request.Headers["Range"] != null)) 
     { 
      //Get the actual byte range from the range header string, and set the starting byte. 
      string[] range = Request.Headers["Range"].Split(new char[] { '=', '-' }); 
      startbyte = Convert.ToInt64(range[1]); 
      if (range.Length > 2 && range[2] != "") endbyte = Convert.ToInt64(range[2]); 
      //If the start byte is not equal to zero, that means the user is requesting partial content. 
      if (startbyte != 0 || endbyte != fSize - 1 || range.Length > 2 && range[2] == "") 
      { statusCode = 206; }//Set the status code of the response to 206 (Partial Content) and add a content range header.          
     } 
     long desSize = endbyte - startbyte + 1; 
     //Headers 
     Response.StatusCode = statusCode; 

     Response.ContentType = "audio/mp3"; 
     Response.AddHeader("Content-Accept", Response.ContentType); 
     Response.AddHeader("Content-Length", desSize.ToString()); 
     Response.AddHeader("Content-Range", string.Format("bytes {0}-{1}/{2}", startbyte, endbyte, fSize)); 
     //Data 

     var stream = new MemoryStream(song, (int)startbyte, (int)desSize); 

     return new FileStreamResult(stream, Response.ContentType); 
    } 
Các vấn đề liên quan