Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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';
        this.Response.AddHeader("Content-Disposition", "test.mp3");
        this.Response.ContentType = "audio/mpeg";

        return View();
}

But how do I return the mp3 file?

like image 236
Harris Avatar asked Dec 04 '22 14:12

Harris


2 Answers

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[].

like image 106
Carles Company Avatar answered Mar 23 '23 13:03

Carles Company


If your MP3 file is in a location accessible to users (i.e. on a website folder somewhere) you could simply redirect to the mp3 file. Use the Redirect() method on the controller to accomplish this:

public ActionResult Stream()
{
    return Redirect("test.mp3");
}
like image 35
Ryan Brunner Avatar answered Mar 23 '23 14:03

Ryan Brunner