ASP NET MVC和HTML5音频 - 文件无法播放

时间:2016-11-28 15:46:36

标签: asp.net-mvc html5-audio

我正在尝试创建一个包含音频文件的表格,当用户点击播放按钮时,该表格应该开始播放。这是我到目前为止所尝试的:

控制器:

    [HttpGet]
    public ActionResult PlayFile(string FilePath)
    {
        WebClient WC = new WebClient();
        WC.Credentials = new System.Net.NetworkCredential("username", "password");
        byte[] buff = WC.DownloadData(FilePath);
        var SplitFileName = FilePath.Split('\\');
        string FileName = "Recording_" + SplitFileName[SplitFileName.Count() - 1];

        Response.AddHeader("Content-Disposition", "inline; filename=" + FileName);
        MemoryStream stream = new MemoryStream(buff);
        return new FileStreamResult(stream, "audio/wav");

        //I have also tried:
        //return File(buff, "audio/wav");
    }

音频标签如下所示:

<td>
  <audio controls preload='none'>
     <source src='/Components/PlayFile?FilePath=[filename.wav]' type='audio/wav'>
  </audio>
</td>

在Chrome中本地运行网站时,所有文件的长度均为0:00,您可以单击播放按钮一次,但不播放该文件。单击播放按钮后,无法再次单击它。但是可以下载该文件 并发挥它。在Firefox中本地运行站点时,文件的长度也为0:00,当您单击播放按钮时,控件将消失。也可以在Firefox中下载该文件。有谁知道这可能导致什么?

2 个答案:

答案 0 :(得分:0)

你可以尝试使用以下功能吗?

public FileResult PlayFile(string FilePath)
{
    return new FilePathResult(FilePath, "audio/wav");
}

另外,如果有帮助,请尝试将“audio / wav”更改为“audio / mp3”。

答案 1 :(得分:0)

问题是音频文件是GSM格式,需要转换为PCM。此代码有效:

[HttpGet]
public ActionResult PlayFile(string FilePath)
{
    WebClient WC = new WebClient();
    WC.Credentials = new System.Net.NetworkCredential("username", "password");
    byte[] buff = WC.DownloadData(FilePath);
    var SplitFileName = FilePath.Split('\\');
    string FileName = "Recording_" + SplitFileName[SplitFileName.Count() - 1];

    MemoryStream ms = new MemoryStream();
    ms.Write(buff, 0, buff.Length);
    ms.Seek(0, SeekOrigin.Begin);

    MemoryStream outputStream = new MemoryStream();

    using (NAudio.Wave.WaveFileReader reader = new WaveFileReader(ms))
    using (NAudio.Wave.WaveStream waveStream = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(reader))
    using (NAudio.Wave.WaveFileWriter waveFileWriter = new WaveFileWriter(outputStream, waveStream.WaveFormat))
    {
            byte[] bytes = new byte[waveStream.Length];
            waveStream.Position = 0;
            waveStream.Read(bytes, 0, (int)waveStream.Length);
            waveFileWriter.Write(bytes, 0, bytes.Length);
            waveFileWriter.Flush();
    }

    return File(outputStream.ToArray(), "audio/wav");
}