Text to Speech C# Program

#r "Newtonsoft.Json"
#r "Microsoft.WindowsAzure.Storage"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Blob;

public static async Task<IActionResult> Run(HttpRequest req, CloudBlockBlob outputBlob, ILogger log)
        {
            string subscriptionKey = "332133";
            string ttsEndpoint = "https://centralindia.tts.speech.microsoft.com/cognitiveservices/v1";
            string accessTokenEndpoint = "https://centralindia.api.cognitive.microsoft.com/sts/v1.0/issuetoken";
            string azureSpeechResourceName = "SampleSpeechText";
            string voice = "Microsoft Server Speech Text to Speech Voice (hi-IN, Hemant)";
            string accessToken = null;
            string text = null;
            if (!string.IsNullOrEmpty(req.Query["text"]))
            {
                text = req.Query["text"];
            }
            else
            {
                return new BadRequestObjectResult("Please pass text you wish to generate on the query string or in the request body using param: text");
            }
            try
            {
                accessToken = await FetchTokenAsync(accessTokenEndpoint, subscriptionKey).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                return new BadRequestObjectResult("Failed to obtain access token.");
            }
            string body = @"<speak version='1.0' xmlns='https://www.w3.org/2001/10/synthesis' xml:lang='hi-IN'>
              <voice name='" + voice + "'>" + text + "</voice></speak>";
            using (var client = new HttpClient())
            {
                using (var request = new HttpRequestMessage())
                {
                    request.Method = HttpMethod.Post;
                    request.RequestUri = new Uri(ttsEndpoint);
                    request.Content = new StringContent(body, Encoding.UTF8, "application/ssml+xml");
                    request.Headers.Add("Authorization", "Bearer " + accessToken);
                    request.Headers.Add("Connection", "Keep-Alive");
                    request.Headers.Add("User-Agent", azureSpeechResourceName);
                    request.Headers.Add("X-Microsoft-OutputFormat", "riff-24khz-16bit-mono-pcm");
                    using (var response = await client.SendAsync(request).ConfigureAwait(false))
                    {
                        response.EnsureSuccessStatusCode();
                        using (var dataStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
                        {
                            await outputBlob.UploadFromStreamAsync(dataStream);
                            return new OkObjectResult(outputBlob.Uri.AbsoluteUri);
                        }
                    }
                }
            }
        }
        public static async Task<string> FetchTokenAsync(string tokenFetchUri, string subscriptionKey)
        {
            using (var client = new HttpClient())
            {
                Console.WriteLine(subscriptionKey);
                Console.WriteLine(tokenFetchUri);
                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
                UriBuilder uriBuilder = new UriBuilder(tokenFetchUri);
                var result = await client.PostAsync(uriBuilder.Uri.AbsoluteUri, null).ConfigureAwait(false);
                return await result.Content.ReadAsStringAsync().ConfigureAwait(false);
            }
        }

Comments

Popular posts from this blog

PUTTY - The server's host key is not cached in the registry cache

OIM-12c Installation - FMW - SOA - IDM

Apache Kafka - Zookeeper