ASP.NET MVC 播放遠程服務器上的MP3文件


問題:

  做需求遇到需要播放遠程服務器上的MP3音頻,使用FTP去獲取文件。但是一般都是在頁面 <audio> 的src 中直接寫文件地址來播放音頻。實在不想做臨時文件,折騰了半天終於可以通過Stream的方式播放音頻了,解決方案如下。

解決步驟:

  1.后台偽代碼如下

  

 1      public ActionResult PlayWav(string id)
 2         {
 3 
 4             try
 5             {
 6             //FTP 直接返回Stream,需要自己實現
 7                 using (Stream fileStream = FTPHelper.FileUpDownload.FtpDownloadStream(id, "", true))
 8                 {
 9                     byte[] fileByte = new byte[fileStream.Length];
10                     fileStream.Seek(0, SeekOrigin.Begin);    
11                     fileStream.Read(fileByte, 0, (int)fileStream.Length);
12                     long fSize = fileStream.Length;
13                     long startbyte = 0;
14                     long endbyte = fSize - 1;
15                     int statusCode = 200;
16                     if ((Request.Headers["Range"] != null))
17                     {
18                         //Get the actual byte range from the range header string, and set the starting byte.
19                         string[] range = Request.Headers["Range"].Split(new char[] { '=', '-' });
20                         startbyte = Convert.ToInt64(range[1]);
21                         if (range.Length > 2 && range[2] != "") endbyte = Convert.ToInt64(range[2]);
22                         //If the start byte is not equal to zero, that means the user is requesting partial content.
23                         if (startbyte != 0 || endbyte != fSize - 1 || range.Length > 2 && range[2] == "")
24                         { statusCode = 206; }//Set the status code of the response to 206 (Partial Content) and add a content range header.                                    
25                     }
26                     long desSize = endbyte - startbyte + 1;
27                     //Headers
28                     Response.StatusCode = statusCode;
29                     Response.ContentType = "audio/mpeg";
30                     Response.AddHeader("Content-Accept", Response.ContentType);
31                     Response.AddHeader("Content-Length", desSize.ToString());
32                     Response.AddHeader("Content-Range", string.Format("bytes {0}-{1}/{2}", startbyte, endbyte, fSize));
33                     return File(fileByte, Response.ContentType);
34                     //return new FileStreamResult(fileByte, Response.ContentType);  這個方法不行
35                 }
36             }
37             catch (Exception ex)
38             {               
39                 throw;
40             }
41         }        

  2.前台頁面代碼如下:

  

1 <audio controls='controls' >
2     <source src='/Controller/PlayWav/test.mp3' type='audio/mpeg' />
3 </audio>

   參考地址:https://stackoverflow.com/questions/31246314/mvc-audio-controls-playing-song-from-bytes


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM