How to send a wav sound file using javascript and webapi c #
I need to send an audio wav file to a webapi controller for Microsoft api message calls. What I've done,
-
Recorded audio is converted to base64 data using client side javascript
-
the webapi controller is called using an ajax call and sends the base64 audio data as well.
3.in webapi controller, converted base64 data to bytes and sent to restpi (microsoft).
please help me how can i make all these steps right
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);
}
source to share
contentType
- the type of data you are sending, therefore application / json; The default is application/x-www-form-urlencoded; charset=UTF-8
.
If you are using application/json
, you must use JSON.stringify()
JSON to send object.
JSON.stringify()
turns javascript text object
into json
and stores it in a string.
data: JSON.stringify({"mydata":base64Data}),
In your controller, you must pass a parameter myData
. Something like that:
FROM#
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);
},
});
FROM#
public async void Post([FromBody] string mydata){
//code
}
source to share