Search code examples
asp.net-mvcbytehtml5-audio

MVC audio controls playing song from bytes


I have my songs stored in database as bytes[]. How do I use these in the <audio> tag.

So something like this. Do I need to convert the bytes to something else first? I am not sure.

foreach (var item in Model)
    {
        <audio controls>
            <source [email protected] type="audio/mp3"/>
        </audio>  
    }

Solution

  • One way would be to add a new action in your controller that returns the data:

    public ActionResult Audio(int someId)
    {
        byte[] songBytes; 
        // Add code to get data
        return new FileStreamResult(songBytes, "audio/mp3");
    }
    

    Then put the URL to that into the src attribute:

    foreach (var item in Model)
    {
        <audio controls>
            <source src="/Controller/Audio/@item.someId" type="audio/mp3"/>
        </audio>  
    }