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

原文地址:https://www.cnblogs.com/GYY2046/p/8073541.html