Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream MP3 file MVC3

I am trying to stream a file using the audio HTML5 tag. I have put the Controller action to return a FileStream and attached it to the src for the audio. However, the content is not loading into the audio tag and doesn't play when I press the default play button. I know the controller is working when I access the src directly. However, it doesn't work in the HTML5 audio tag.

Can anyone tell me what I am missing?

like image 476
Clay Wright Avatar asked Jan 18 '12 03:01

Clay Wright


1 Answers

You should not return a FileStream, you should return a FileStreamResult or a FilePathResult from your controller action, like this:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult MyAudio()
    {
        var file = Server.MapPath("~/app_data/test.mp3");
        return File(file, "audio/mp3");
    }
}

and the ~/Views/Home/Index.cshtml view:

@{
    Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Sound Sample</title>
</head>
<body>
    <article class="audio">
        <header>
            <h2>Some audio</h2>
        </header>

        <audio controls>
            <source src="@Url.Action("myaudio")" type="audio/mp3" />
            <p>Your browser does not support HTML 5 audio element</p>
        </audio>
    </article>
</body>
</html>
like image 107
Darin Dimitrov Avatar answered Sep 20 '22 08:09

Darin Dimitrov