How to stream an MP3 from an ASP.NET MVC Controller Action

前端 未结 7 1544
时光说笑
时光说笑 2020-12-29 16:31

I have an mp3 file in my site. I want to output it as a view. In my controller I have:

public ActionResult Stream()
{
        string file = \'test.mp3\';
            


        
相关标签:
7条回答
  • 2020-12-29 17:05

    You should return a FileResult instead of a ViewResult:

     return File(stream.ToArray(), "audio/mpeg", "test.mp3");
    

    The stream parameter should be a filestream or memorystream from the mp3 file.

    0 讨论(0)
  • 2020-12-29 17:08

    Create an Action like this:

    public ActionResult Stream(string mp3){
        byte[] file=readFile(mp3);
        return File(file,"audio/mpeg");
    }
    

    The function readFile should read the MP3 from the file and return it as a byte[].

    0 讨论(0)
  • 2020-12-29 17:08

    You don't want to create a view, you want to return the mp3 file as your ActionResult.

    Phil Haack made an ActionResult to do just this, called a DownloadResult. Here's the article.

    The resulting syntax would look something like this:

    public ActionResult Download() 
    {
      return new DownloadResult 
        { VirtualPath="~/content/mysong.mp3", FileDownloadName = "MySong.mp3" };
    }
    
    0 讨论(0)
  • 2020-12-29 17:12
    public FileResult Download(Guid mp3FileID)
            {
                string mp3Url = DataContext.GetMp3UrlByID(mp3FileID);
    
                WebClient urlGrabber = new WebClient();
                byte[] data = urlGrabber.DownloadData(mp3Url);
                FileStream fileStream = new FileStream("ilovethismusic.mp3", FileMode.Open);
    
                fileStream.Write(data, 0, data.Length);
                fileStream.Seek(0, SeekOrigin.Begin);
    
                return (new FileStreamResult(fileStream, "audio/mpeg"));
                //return (new FileContentResult(data, "audio/mpeg"));
    
            }
    
    0 讨论(0)
  • 2020-12-29 17:14

    You should create your own class which inherits from ActionResult, here is an example of serving an image.

    0 讨论(0)
  • 2020-12-29 17:16

    Why not use the Filepathresult?

    Like this :

            public FilePathResult DownLoad()
        {
            return new FilePathResult(Url.Content(@"/Content/01.I Have A Dream 4'02.mp3"), "audio/mp3");
        }
    

    And create the download link:

    <%=Html.ActionLink("Download the mp3","DownLoad","home") %>
    
    0 讨论(0)
提交回复
热议问题