如何在asp.net mvc中使用html5播放mp3内存流

本文关键字:html5 播放 mp3 内存 asp net mvc | 更新日期: 2023-09-27 18:07:28

我将mp3文件存储在SQL Server的varbinary列中。我可以通过动作方法GetVnAudioStream检索byte[]数组。

当用户点击视图中的链接时,我如何让浏览器使用html5播放声音?提前感谢您的帮助。

我有以下控制器和视图:

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;
    }
}

视图:

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

由于某种原因,如果我在物理存储的文件上使用这个控制器,那么一切都工作得很好:

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

如何在asp.net mvc中使用html5播放mp3内存流

我明白了:操作方法的返回类型必须来自类型File而不是FileStreamResult。所以基本上没有必要使用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;
    }