简体   繁体   中英

How to send wav audio file using javascript and webapi c#

i need to send an audio wav file to the webapi controller for the microsoft bing speech api calls . what i have done is ,

  1. Recorded audio converted to base64 data using javascript in the client side

  2. invoked webapi controller using ajax call and sends the base64 audio data as well.

    3.in webapi controller , converted the base64 data to bytes and sends to the restpi (microsoft).

please help me how i can do all these steps correctly

ajax call ,

$.ajax({
            url: 'http://localhost:49818/api/voice',
            type: 'POST',
            data: base64Data,
            dataType: 'json',
            contentType: "application/json",
            success: function (data) {

                alert(data);
            },

webapi controller method

string b64 = Request.Content.ReadAsStringAsync().Result;
            //string text = System.IO.File.ReadAllText(@"D:\\base64.txt");
            var client = new HttpClient();
            byte[] toBytes1 = Encoding.ASCII.GetBytes(b64);
var uri = "https://westus.api.cognitive.microsoft.com/spid/v1.0/identificationProfiles/a1cb4a95-9e09-4f54-982b-09632aee7458/enroll?shortAudio=true";

            HttpResponseMessage response;
            byte[] toBytes = Encoding.ASCII.GetBytes(b64);
            using (var content = new ByteArrayContent(toBytes))
            {

                content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                //content.Headers.ContentType = new MediaTypeHeaderValue("audio/wav");

                response = await client.PostAsync(uri, content);


            }

contentType is the type of data you're sending, so application/json; The default is application/x-www-form-urlencoded; charset=UTF-8 application/x-www-form-urlencoded; charset=UTF-8 .

If you use application/json , you have to use JSON.stringify() in order to send JSON object.

JSON.stringify() turns a javascript object to json text and stores it in a string.

data: JSON.stringify({"mydata":base64Data}),

In your controller you have to pass a parameter called myData .Something like this:

C#

public ActionResult MyMethod(string mydata){
   //code
}

UPDATE

$.ajax({
    url: 'http://localhost:49818/api/voice',
    type: 'POST',
    data:{"mydata":base64Data},
    dataType: 'json',
    success: function (data) {
        alert(data);
    },
});

C#

public async void Post([FromBody] string mydata){
   //code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM