Benjamin Martin
Benjamin Martin

Reputation: 747

How to play mp3 memorystream with html5 in asp.net mvc

I store my mp3 files in a SQL Server in a column as varbinary. I can retrieve the byte[] arrays through the action method GetVnAudioStream.

How can I let the browser play the sound using html5 when the user click on a link in the view? Thanks in advance for your help.

I have the following controller and view:

public class LookUpController : Controller
{
    protected IBabbelerRepository babbelerRepo;

    /// <summary>
    /// Konstruktor des Controllers.
    /// </summary>
    /// <param name="repo"></param>
    public LookUpController(IBabbelerRepository repo)
    {
        this.babbelerRepo = repo;
    }

    // GET: KeywordSearch
    public ActionResult LookUpIndex()
    {
        return View();
    }


    [HttpGet]
    public ActionResult GetVnAudioStream(int id)
    {
        FileStreamResult audioResult = null;
        if (id > 0)
        {
            var pronunciation = babbelerRepo.GetVnPronunciationById(id);
            if (pronunciation != null && pronunciation.Length > 0)
            {
                MemoryStream stream = new MemoryStream();
                stream.Write(pronunciation, 0, pronunciation.Length);
                audioResult =  new FileStreamResult(stream, "audio/mp3");                    
            }
        }
        return audioResult;
    }
}

View:

<tbody>
    <tr>
        <td><audio controls><source src="@Url.Action("GetVnAudioStream", "LookUp", new {id=15})" type="audio/mp3" /></audio></td>
    </tr>
</tbody>

For some reason, if i use this controller on a physically stored file then everything works well:

    var file = Server.MapPath("~/app_data/test.mp3");
    return File(file, "audio/mp3");

Upvotes: 1

Views: 3645

Answers (1)

Benjamin Martin
Benjamin Martin

Reputation: 747

I got it: The return type of the action method must be from type File and not FileStreamResult. So basically there is no need to use MemoryStream:

    [HttpGet]
    public ActionResult GetVnAudioStream(int id)
    {
        if (id > 0)
        {
            var pronunciation = babbelerRepo.GetVnPronunciationById(id);
            if (pronunciation != null && pronunciation.Length > 0)
            {
                return File(pronunciation, "audio/mp3");
            }
        }
        return null;
    }

Upvotes: 1

Related Questions