Guide on transferring a wav audio file with javascript and webapi in C#

In order to send an audio wav file to the WebAPI controller for Microsoft Bing Speech API calls, the following steps have been taken:

  1. The audio was recorded and converted to base64 data using JavaScript on the client side.

  2. An AJAX call was made to invoke the WebAPI controller and send the base64 audio data as well.

  3. Within the WebAPI controller, the base64 data was converted to bytes and sent to the RESTful API provided by Microsoft.

If you can provide guidance on how to correctly execute these steps, it would be greatly appreciated.

Here is the AJAX call:

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

And here is the WebAPI controller method:

string b64 = Request.Content.ReadAsStringAsync().Result;
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);
}

Answer №1

contentType refers to the type of data being sent, such as application/json; The default is

application/x-www-form-urlencoded; charset=UTF-8
.

If you opt for application/json, remember to use JSON.stringify() to send a JSON object.

JSON.stringify() converts a javascript object into a json text and saves it in a string.

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

In your controller, ensure that you pass a parameter named myData. This can be done 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
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a build error with Ubuntu, Node-Gyp, and Canvas – help needed!

Hey there, I'm having some trouble with installing the Canvas package. I've tried Package Versions 6.1.13 and 6.1.3 Here are my system details: Ubuntu 18.04.5, Node 12.18.4 LTS, Python 2.7, g++ installed, pkg-config installed, libjpeg installed ...

Step-by-step guide on mocking an asynchronous function in nodejs with jest

Within this function, I need to mock the httpGet function so that instead of calling the actual function and returning its value, it will call a simulated function fetchStudents: async(req,classId) => { let response = await httpGet(req); return r ...

Looking to receive a 405 error message (Method Not Allowed) instead of the typical 404 error?

My goal is to trigger 405 errors when a valid route is provided but the HTTP method is not found. Currently, my application returns 404s because it requires both the route and method to match in the function (as expected in MVC). [HttpGet("api/action")] p ...

Getting data from a document containing key value pairs

I have a collection of text files that are structured in a key-value pair format. "Site Code": "LEYB" "Also known as": "" "Location": "Pier Site, Poblacion del Sur, Villaba, Southern Leyte" "Contact person(s)": "" "Coordinates[1]": "11 ...

Next-auth is in need of a username for the credentials provider

I am currently trying to learn how to implement next-auth in Next.js 13. I have set up a credentials login system with username and password. When I make an API request, I expect to receive a status code of 200 if the credentials are correct. The logic f ...

Sending a JSON file to a PHP script

I need help passing a JSON file to PHP using jQuery. When I check the response, I receive an error stating "json_decode expects parameter 1 to be a string." Below is my jQuery routine: $("#ProcessData").click(function(){ var cols = $("#tblGroup thead t ...

Is it possible for me to convert my .ejs file to .html in order to make it compatible with Node.js and Express?

I have an index.html file and I wanted to link it to a twitter.ejs page. Unfortunately, my attempts were unsuccessful, and now I am considering changing the extension from ejs to html. However, this approach did not work either. Do .ejs files only work wit ...

Looking to add elements to a specific div dynamically using jQuery? Let's explore how to insert comments seamlessly

I would like to implement a comment system that adds entered comments to a specific div. Here's the code I have so far: <ul class="comments"> <li> <a class="commenter_name" href="/">Dushyanth Lion</a> ...

developing a dropdown menu feature

I'm struggling with a small issue related to my drop-down menu function. My goal is to hide the visibility of a menu tab after it has been clicked for the second time. Below is the code snippet I've been working on: HTML:- <nav class="clea ...

inline editing feature for datatables with the ability to upload files

Hey there, I'm struggling with integrating image upload functionality into my inline datatable edit. I can't seem to figure out how to pass the image to PHP via AJAX. I've tried a few different approaches but haven't been successful so ...

What is the best way to utilize Ajax and Jquery in order to retrieve data from a PHP database and dynamically update elements with the fetched information?

I am currently enhancing a website to simplify the process for employees when editing products. At present, in order to change prices, someone has to log in to the database and manually alter them, followed by making adjustments to the HTML of the website ...

JavaScript communication between clients and servers

I am looking to develop two scripts, one for the client-side and one for the server-side. I came across a snippet that allows for asynchronous calling of JavaScript: <html> <head> </head> <body> <script> (function() { ...

Looking to showcase website HTML code by simply clicking on a banner image?

I am looking to implement a feature where banner HTML code is displayed in a popup on website when the banner is clicked. For instance, an example of a banner could be: <img src="https://myweb.com/images/banners/1.gif"> Upon clicking the banner im ...

The attempt to save data failed with a timed out error for Operation `todos.insertOne()` after 10000ms of buffering

const express=require("express"); const { stringify } = require("querystring"); const router= express.Router() const Db=require("../models/Db") router.get("/",(req,res)=>{ res.render("index.hbs"); }) .post("/addData",async(req,res)=>{ const ...

Improprove the efficiency of flattening an array containing nested JSON objects using JavaScript

Supposed to be an array structured like this: [ { "key_set1": { int_val: 3, arr_val: [ 1, 3, 4 ] } }, { "key_set2": { stri ...

How can we avoid re-rendering the same component repeatedly when using React Router v6?

As a beginner in react, I'm facing an issue with preventing components from re-rendering when navigating to a different page. Specifically, I want to display only text on my Signup and Login pages, but the Navbar keeps re-rendering every time I switch ...

Guide on incorporating jQuery accordion within a specific div element through ajax loading?

I am facing an issue with my jQuery accordion. It functions properly when viewed on its own, but when I try to load it into a div on my home page using a link and the load method, it loses all functionality and appears as a list with headings. You can see ...

Strange error message: Attempting to set properties of null (changing 'innerHTML')

I have been working on a project where I am creating a website that retrieves data from a specified URL, displays it on the front end, and performs certain functionalities with that data (although this part is not yet implemented). However, I have encounte ...

Svelte is unable to bring in

Hey there, I'm new to Svelte and currently working on a simple feedback app. I have divided my project into two files - one for the main app and another for a list of feedbacks. Here is my App.svelte file: <script> import feedback from ". ...

When the user presses either the refresh button or the back button, they will be redirected

After the user presses refresh or uses the browser back button, I need to redirect them to a specific page in order to restart the application. My JavaScript code is as follows: var workIsDone = false; window.onbeforeunload = confirmBrowseAway; function ...