1

I have this Webservice method that I use to get audio from the database. Server-side:

[WebMethod]
  public void PlayAudio(int id)
  {
      byte[] bytes = new byte[0];
      using (The_FactoryDBContext db = new The_FactoryDBContext())
      {
          if (db.Words.FirstOrDefault(word => word.wordID == id).engAudio != null)
          {
              bytes = db.Words.FirstOrDefault(word => word.wordID == id).engAudio;

              MemoryStream ms = new MemoryStream(bytes);



            Context.Response.Clear();
            Context.Response.AddHeader("ContentType ", "audio/wav");
            Context.Response.BinaryWrite(ms.ToArray());
            Context.Response.Flush();
            Context.Response.Close();
          }
     }
  }

I have this code to play this audio in the browser:

var audio = document.createElement('audio');

            audio.id = "test";
            audio.autoplay = false;
            audio.preload = true;
            audio.oncanplaythrough = function () {
                foo.disabled = false;
            };
            var id = $("[id$=hiddenWord_id]").val();


            audio.src =// below are the different ways ive tried


            foo.onclick = function () {
                audio.play();
            }

I have tried this both this:

audio.src = "../../WebService.asmx/PlayAudio/?id=" + id;

and this to reach the webservie

document.getElementById('test').src = PlayAudio();

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

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

            };

However none of the above seem to work.

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Lulutho Mgwali
  • 823
  • 1
  • 11
  • 33
  • What happens in your javascript? Does it error? Do you pass into success but data is empty or something? – peacedog Oct 01 '15 at 22:38
  • On button click, nothing happens. I put a break point in my Webservice code and the id is never sent. The code never reaches the breakpoint, – Lulutho Mgwali Oct 01 '15 at 22:44
  • Are you making it to the ajax call though? – peacedog Oct 01 '15 at 22:45
  • No i am not. I had to test that quickly. – Lulutho Mgwali Oct 01 '15 at 22:56
  • Why did you use an ASMX webservice? It creates a SOAP service which needs specific headers and action methods you're not supplying with your POST JSON request. You should either rewrite your problem to WebAPI or use a simple ASHX handler. – Niels V Oct 02 '15 at 09:50

2 Answers2

1

Rewrite it to an ASHX. Include the following class (add namespace and using statements yourself, name the file for instance AudioHandler.ashx.cs):

public class AudioHandler : IHttpHandler
{
    public bool IsReusable
    {
        get { return true; }
    }

    public void ProcessRequest(HttpContext context)
    {
        int id = Convert.ToInt32(context.Request.QueryString["id"]);
        byte[] bytes = new byte[0];
        using (The_FactoryDBContext db = new The_FactoryDBContext())
        {
            if (db.Words.FirstOrDefault(word => word.wordID == id).engAudio != null)
            {
                bytes = db.Words.FirstOrDefault(word => word.wordID == id).engAudio;

                context.Response.ContentType = "audio/wav";
                context.Response.BinaryWrite(bytes);
                context.Response.Flush();
            }
        }
    }

}

Depending on your .NET version add a handler by specifying it in the web.config or add an audiohandler.ashx file in the root of your site. Paste the following contents in it:

<%@ WebHandler Language="C#" Class="AudioHandler" %>

Now you can call the service by

audio.src = "/AudioHandler.ashx?id=" + id;

You can extend the ASHX file to make it more robust (what if no ID is present or it isn't a valid integer for instance)

Niels V
  • 1,005
  • 8
  • 11
  • What do you mean with called on page load and not on button click? Is that the audio is playing, but not when you click the button? Because in that case your server side code is working and there is only an issue left with the client code. – Niels V Oct 04 '15 at 07:54
0

This is what I have done in my case.

var url = "http://excample.com/get/bytes"
var audio;
audio = $('audio');

fetch(url, {
    method: 'GET',
    headers: {
        'Authorization': 'Bearer ABCDEFGHIJKLMNO'
    }
}).then(response => {
    response.blob()
        .then(blob => {
            const objectUrl = URL.createObjectURL(blob);
            audio[0].src = objectUrl;
        }).catch(e => {
            console.error(e);
        })
}).catch(error => {
    console.error(error);
});
Munam Yousuf
  • 431
  • 1
  • 6
  • 17