1

Let me explain the scenario -

I have a custom web API created for an application which has multiple parameters, the user call this api by passing multiple parameters which are concatenated based on some logic and then inside this custom api it calls Azure speech API to convert Text to Speech (in 2 steps - 1. I call the Azure speech service to get the token, 2. I call the Azure speech service to convert the text to speech)

The problem - When I call the Azure speech service to fetch the token, it stays in a endless loop.

Below is the sample code, any pointers in right direction will be helpful -

public class ConverterController : ApiController
{
    

    /// <summary>
    /// default constructor
    /// </summary>
    public ConverterController()
    {
    }

    
    [HttpGet]
    public HttpResponseMessage ConvertUsingSpeech([FromUri] OutReachMessage outReachMessage)
    {

        try
        {
            outReachMessage = new OutReachMessage();
            var result = ConvertUsingSpeechApi(outReachMessage);
            var response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new StringContent(OutputMp3FilePath);
            return response;
        }
        catch (Exception ex)
        {
            return new HttpResponseMessage(HttpStatusCode.InternalServerError);
        }
    }


    async Task ConvertUsingSpeechApi(OutReachMessage outReachMessage)
    {
        var authObj = new Authentication("key");
        var token = authObj.GetAccessToken();


        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", token);
            client.DefaultRequestHeaders.Add("Content-Type", contentType);
            client.DefaultRequestHeaders.Add("X-Microsoft-OutputFormat", outputFormat);
            UriBuilder uriBuilder = new UriBuilder(fetchSpeechUri);

            var content = new StringContent("<speak version='1.0' xml:lang='hi-IN'><voice xml:lang='hi-IN' xml:gender='Female' name = 'hi-IN-SwaraNeural'>" +
    "Welcome mahesh to the world of Azure - feeling great. </voice></speak>",
                            Encoding.UTF8, "text/xml");

            var result = await client.PostAsync(uriBuilder.Uri.AbsoluteUri, content);

            using (var response = client.PostAsync(uriBuilder.Uri.AbsoluteUri, content).Result)
            using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync())
            {
                string fileToWriteTo = OutputMp3FilePath;
                using (Stream streamToWriteTo = File.Open(fileToWriteTo, FileMode.Create))
                {
                    await streamToReadFrom.CopyToAsync(streamToWriteTo);
                }
            }
        }
    }

}

authentication class - which fetchs the token

public class Authentication
{
    public static readonly string FetchTokenUri =
    "https://centralindia.api.cognitive.microsoft.com/sts/v1.0/issueToken";
    private string subscriptionKey;
    private string token;

    public Authentication(string subscriptionKey)
    {
        this.subscriptionKey = subscriptionKey;
        this.token = FetchTokenAsync(FetchTokenUri, subscriptionKey).Result;
    }

    public string GetAccessToken()
    {
        return this.token;
    }

    private async Task<string> FetchTokenAsync(string fetchUri, string subscriptionKey)
    {
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
            UriBuilder uriBuilder = new UriBuilder(fetchUri);

            var result = await client.PostAsync(uriBuilder.Uri.AbsoluteUri, null);
            Console.WriteLine("Token Uri: {0}", uriBuilder.Uri.AbsoluteUri);
            return await result.Content.ReadAsStringAsync();
        }
    }
}

Note - I am able to call the Azure Speech api with postman and also with console application, only when I call the azure service inside my custom webapi it doesnot works.

Jason Pan
  • 15,263
  • 1
  • 14
  • 29
Ish Tech
  • 239
  • 1
  • 2
  • 12
  • If you need further help, pls let me know. – Jason Pan Mar 15 '21 at 08:43
  • If my reply is helpful, please accept it as answer(click on the mark option beside the reply to toggle it from greyed out to fill in.), see https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Jason Pan Mar 26 '21 at 08:11

1 Answers1

0

Change code like below, delete string subscriptionKey. It will work.

public Authentication()
{
    this.subscriptionKey = subscriptionKey;
    this.token = FetchTokenAsync(FetchTokenUri, subscriptionKey).Result;
}
Jason Pan
  • 15,263
  • 1
  • 14
  • 29