How to play wave file in MVC 4

1k views Asked by At

I'm trying to implement a way to play wave files in my mvc application. In my controller I basically grab the byte data from the db, create a temp wave file and write the byte into the file. Then on my webgrid if the user clicks any row in the wave file column in triggers an ajax call to play the wave file. This is what I have so far:
Controller

          dt.Columns.Add("WavFile", typeof(string));
                foreach (DataRow dr in dt.Rows)
                {
                    try
                    {
                        if (dr["CallerAuthorization"] != null && dr["CallerAuthorization"].ToString() != "")
                        {
                            Byte[] tempAudio = (Byte[])dr["CallerAuthorization"];
                            if (tempAudio.Length > 0)
                            {
                                dr["WavFile"] = CreateWavFile(tempAudio);
                            }
                            else
                            {
                                dr["WavFile"] = "";
                            }
                        }
                        else
                        {
                            dr["WavFile"] = "";
                        }

                    }
                    catch (Exception e)
                    {
                        if (e.Source != null)
                            Console.WriteLine(e.Source);
                        throw;
                    }
                }


public string CreateWavFile(Byte[] authorization)
   {
       string tempDir = Path.GetTempFileName();
       tempDir = tempDir.Substring(0, tempDir.Length - 4);
       tempDir = tempDir + ".wav";
       WaveFormat waveFormat = new WaveFormat(4000, 8, 2);
        using (WaveFileWriter ww = new WaveFileWriter(tempDir, waveFormat))
        {
            ww.Write(authorization, 0, authorization.Length);
        }

       return tempDir;
   }

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

View

<script>
$(document).ready(function () {
    $(".audiobtn").click(function () {

            $.ajax({
                type: "POST",
                url: "/SearchPayment/PlayAuthorization",
                data: { audio: $(this).find('img').attr('alt') },
                cache: false,
                success: function (response) {

                },
                error: function (error) {
                    alert("Unable to play audio");
                    console.log(error);
                }
             });
        })
    })
</script>  

<div style="display:none">
<audio controls preload="none">
    <source src='response' type='audio/wav' />
</audio>

But it's not playing the wave file

Can anyone tell me what I'm doing wrong and how I can fix this?

Thank you

Update I changed my implementation to play on the client side

<script type="text/javascript">
$(document).ready(function () {
    $(".audiobtn").click(function () {

        $.ajax({
            type: "POST",               
            url: "/SearchPayment/PlayAuthorization",
            data: { audio: $(this).find('img').attr('alt') },
            async: false,
            cache: false,
            success: function (src) {
                PlayWave(src);
                $("#ContextMenu").fadeOut(80);
            },
            error: function (error) {
                alert("Unable to play audio");                          
                console.log(error);
            }
        });
    })

    function PlayWave(srcUrl) {
        $('#waveSrc').attr("src", srcUrl);
        $("audio")[0].play();
    }
}) 
</script>

<div style="display:none">
    <audio controls preload="none">
        <source src="~/Content/authorization.wav" type="audio/wav" />
    </audio>
</div>

[HttpPost]
public FileResult PlayAuthorization(string audio)
{
    byte[] authorization = Convert.FromBase64String(audio);
    string audioContents = 
Request.MapPath("~/Content/authorization.wav");
    string newAudio = audioContents;
    FileInfo wavFile = new FileInfo(audioContents);
    wavFile.Delete();

    System.IO.File.WriteAllBytes(audioContents, authorization);

    return new FilePathResult(audioContents, "audio/wav");
}

It play the first wav file it creates just fine, but when the application deletes it and creates a new wav file "~/Content/Authorization.wav" it keeps playing the previous wav file and not the new one.

What can I do to fix this? Is there a way to dynamically create a new wav file for each data I have and how can I pass it to my audio tag? cause the way I implemented it, it won't play unless I specify the url of the wav file in the tag

Thank you

0

There are 0 answers