Search code examples
javascriptc#htmlaudioasp.net-mvc-5

HTML5 audio element with source being audio stored as varbinary bytes from database


This is a normal audio player, but if i wanted my source to be audio stored in my database how would i go about achieving this ?

<audio controls="controls" autoplay="true" loop="loop">
<source src="WhiteChristmas.mp3"/>
</audio>

This how i am currently reading the audio files from my database using a WebService.

 [WebMethod]
    public void PlayXhosa(int id)
    {

        using (The_FactoryDBContext db = new The_FactoryDBContext())
        {
            if (db.Words.FirstOrDefault(word => word.wordID == id).xhosaAudio != null)
            {
                byte[] bytes = db.Words.FirstOrDefault(word => word.wordID == id).xhosaAudio;

                MemoryStream ms = new MemoryStream(bytes);
                System.Media.SoundPlayer myPlayer = new System.Media.SoundPlayer(ms);
                myPlayer.Play();
            }
        }

    }

This is what my client-side code looks like at the moment

function PlayXhosa() {
                var id = $("[id$=hiddenWord_id]").val();
                $.ajax({

                    url: "../../WebService.asmx/PlayXhosa",
                    data: "{ 'id': '" + id + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {

                    }
                });
            };

I then attempt to to call this function like this:

 var audio = document.createElement('audio');
 audio.autoplay = false;
 audio.oncanplaythrough = function() {
 foo.disabled = false;
    };
   audio.src = 'PlayXhosa()';
   foo.onclick = function() {
     audio.play();

}

Then there is the button.

  <button id="foo" disabled>play xhosa audio</button>

Solution

  • I was able to get the answer to this question by asking another slighty different but nonetheless the same question.

    https://stackoverflow.com/a/32904927/5179424