0

I have been trying to implement Microsoft Cognitive Speech-to-text API to convert an audio file to text but always I am getting a Bad Request message.

Here is sample code I am implementing:

public static object MC()
{
    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
    client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", speechKey);
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("audio/wav"));

    var mp = new MultipartFormDataContent();
    var file = new StreamContent(File.OpenRead(HttpContext.Current.Server.MapPath("~/audios/audio_06012023094443961.wav")));
    file.Headers.ContentType = new MediaTypeHeaderValue("audio/wav");
    mp.Add(file, "audio", "audio_06012023094319156.wav");

    var resp = client.PostAsync("https://" + speechRegion + ".stt.speech.microsoft.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US", mp);
    while (!resp.IsCompleted)
    {
        Thread.Sleep(100);
    }
    return resp.Result.ReasonPhrase;
}

My programming language is C#.

  • 1
    It might be a lot of reasons that you have Bad Request. I suggest that after making the API request, check the response for any error messages or additional details that may help identify the issue. You can access the response using `resp.Result.Content.ReadAsStringAsync().Result` to get the response content as a string. – Selim Yildiz Apr 26 '23 at 06:41
  • Here is the message I received using resp.Result.Content.ReadAsStringAsync().Result: No audio data received even though I am attaching the audio file. – Sarbjit Singh Apr 26 '23 at 06:48
  • So ensure that the file path in `File.OpenRead()` is correctly pointing to the location of your audio file on the server. Make sure that the file exists at the specified path and has the correct format – Selim Yildiz Apr 26 '23 at 07:06
  • I have checked thoroughly that the file path is correct and the particular file does exist at that location. Do I need to change code for that? – Sarbjit Singh Apr 26 '23 at 07:21
  • Then I guess you just need to change file name for `audio_06012023094443961.wav` – Selim Yildiz Apr 26 '23 at 18:52
  • As suggested by you, I also tried changing the name of the audio but same response. No audio data received – Sarbjit Singh Apr 27 '23 at 10:15
  • Still finding a solution for the problem above. Any one expert here. – Sarbjit Singh May 04 '23 at 07:29

0 Answers0