Esempio n. 1
0
        public async Task <IActionResult> TextToSpeech([FromBody] JObject request)
        {
            var         watch      = System.Diagnostics.Stopwatch.StartNew();
            string      methodName = "TextToSpeech";
            ResponseDTO response   = new ResponseDTO();

            try
            {
                Log.Write(appSettings, LogEnum.DEBUG.ToString(), label, className, methodName, $"REQUEST: {JsonConvert.SerializeObject(request)}");
                TextToSpeechRequest requestBody = request.ToObject <TextToSpeechRequest>();
                response.Result = await Task.Run(() => TextToSpeechService.TextToSpeech(appSettings, requestBody));

                response.Success = true;
                watch.Stop();
                Log.Write(appSettings, LogEnum.DEBUG.ToString(), label, className, methodName, $"RESULT: {JsonConvert.SerializeObject(response)} Execution Time: {watch.ElapsedMilliseconds} ms");
                return(Ok(response));
            }
            catch (Exception e)
            {
                response.Success = false;
                response.Msg     = e.Message;
                watch.Stop();
                Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {JsonConvert.SerializeObject(request)}");
                Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {e.Source + Environment.NewLine + e.Message + Environment.NewLine + e.StackTrace}");
                return(BadRequest(response));
            }
        }
        // GET: Recipes
        public ActionResult Index()
        {
            if (TempData["RecipeResults"] != null)
            {
                var model = TempData["RecipeResults"] as List <RecipeResult>;
                return(View(model));
            }

            var binDirectoryPath = Server.MapPath("~/bin");
            var wavFileLocation  = string.Format(@"{0}\Assets\AudioFile.wav", binDirectoryPath);

            var response   = SpeechToTextService.Interupt(wavFileLocation);
            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            var result     = serializer.Deserialize <CogResponse>(response);

            var items = result.Results.First().Lexical.Split(' ').ToList();

            var output = RecipeLookupService.Query(items);

            var topOne = output.Results.First().Title;

            var reply = string.Format("There are many options but aye recommend {0}", topOne);

            TextToSpeechService.Speak(reply);
            return(View(output.Results));
        }
Esempio n. 3
0
 public void CreateClients()
 {
     try
     {
         if (settingsService.settings.ibmSettings.textToSpeechAPIKey != "" && settingsService.settings.ibmSettings.speechToTextAPIKey != "" &&
             settingsService.settings.ibmSettings.speechToTextURL != "" && settingsService.settings.ibmSettings.textToSpeechURL != "")
         {
             textToSpeechTokenOptions = new TokenOptions
             {
                 IamApiKey  = settingsService.settings.ibmSettings.textToSpeechAPIKey,
                 ServiceUrl = settingsService.settings.ibmSettings.textToSpeechURL
             };
             speechToTextTokenOptions = new TokenOptions
             {
                 IamApiKey  = settingsService.settings.ibmSettings.speechToTextAPIKey,
                 ServiceUrl = settingsService.settings.ibmSettings.speechToTextURL
             };
             textToSpeechClient = new TextToSpeechService(textToSpeechTokenOptions);
             speechToTextClient = new SpeechToTextService(speechToTextTokenOptions);
         }
     }
     catch (Exception e)
     {
         Console.WriteLine($"IBM credentials not set. Error: {e}");
         MessageBox.Show($"IBM credentials not set. Error: {e}");
     }
 }
Esempio n. 4
0
        public JsonResult ProcesarWatsonTTS(String texto)
        {
            object result = null;

            try
            {
                TextToSpeechService text_to_speech = new TextToSpeechService(Auth.Watson_TTS.Username, Auth.Watson_TTS.Password);
                var results    = text_to_speech.Synthesize(texto, Voice.ES_SOFIA, AudioType.WAV);
                var fileStream = new FileStream("resources/audioTTS.wav", FileMode.Create, FileAccess.Write);
                results.CopyTo(fileStream);
                fileStream.Dispose();

                result = new {
                    data   = "tts.wav",
                    status = "Ok"
                };
            }
            catch (Exception ex)
            {
                result = new {
                    data   = ex.Message,
                    status = "Error"
                };
            }

            return(Json(result));
        }
Esempio n. 5
0
        public IEnumerator MyCoroutine()
        {
            string text = Text.text;

            while (!authenticator.CanAuthenticate())
            {
                yield return(null);
            }

            textToSpeechService = new TextToSpeechService(authenticator);
            textToSpeechService.SetServiceUrl("https://gateway-lon.watsonplatform.net/text-to-speech/api");

            byte[]    synthesizeResponse = null;
            AudioClip clip = null;

            textToSpeechService.Synthesize(
                callback: (DetailedResponse <byte[]> response, IBMError error) =>
            {
                synthesizeResponse = response.Result;
                clip = WaveFile.ParseWAV("hello_world.wav", synthesizeResponse);
                AudioSource audioSource = GetComponent <AudioSource>();
                audioSource.clip        = clip;
                audioSource.Play();
            },
                text: text,
                voice: voice,
                accept: "audio/wav"
                );

            while (synthesizeResponse == null)
            {
                yield return(null);
            }
        }
Esempio n. 6
0
        private async void FalarMensagem()
        {
            //Rd6JgXi2SiivDo02qoGlf2fzh88qf71rNhOVEhuPrzQG

            string           texto         = "Seja bem-vindo";
            IamAuthenticator authenticator = new IamAuthenticator(
                apikey: "Rd6JgXi2SiivDo02qoGlf2fzh88qf71rNhOVEhuPrzQG");

            TextToSpeechService service = new TextToSpeechService(authenticator);

            service.SetServiceUrl("https://stream.watsonplatform.net/text-to-speech/api");

            var result = service.Synthesize(
                text: texto,
                accept: "audio/wav",
                voice: "pt-BR_IsabelaVoice"
                );

            using (FileStream fs = File.Create("nsf_texto_voz.wav"))//Cria um arquivo físico no meu HD
            {
                result.Result.WriteTo(fs);
                fs.Close();
                result.Result.Close();
            }

            AudioPlayer player = new AudioPlayer();
            await player.SetFileAsync("nsf_texto_voz.wav", "nsf_texto_voz.wav"); //Rodam ao mesmo tempo (as duas linhas)

            await player.PlayAsync();
        }
Esempio n. 7
0
        public void Setup()
        {
            if (string.IsNullOrEmpty(credentials))
            {
                try
                {
                    credentials = Utility.SimpleGet(
                        Environment.GetEnvironmentVariable("VCAP_URL"),
                        Environment.GetEnvironmentVariable("VCAP_USERNAME"),
                        Environment.GetEnvironmentVariable("VCAP_PASSWORD")).Result;
                }
                catch (Exception e)
                {
                    Console.WriteLine(string.Format("Failed to get credentials: {0}", e.Message));
                }

                Task.WaitAll();

                var vcapServices = JObject.Parse(credentials);
                _endpoint = vcapServices["text_to_speech"]["url"].Value <string>();
                _username = vcapServices["text_to_speech"]["username"].Value <string>();
                _password = vcapServices["text_to_speech"]["password"].Value <string>();
            }

            _service          = new TextToSpeechService(_username, _password);
            _service.Endpoint = _endpoint;
        }
Esempio n. 8
0
        public void TextToSpeechV1WithLoadedCredentials_Success()
        {
            TextToSpeechService service = new TextToSpeechService();

            Assert.IsTrue(!string.IsNullOrEmpty(service.ApiKey));
            Assert.IsTrue(!string.IsNullOrEmpty(service.Url));
        }
        private void AddWords()
        {
            IamAuthenticator authenticator = new IamAuthenticator(
                apikey: "{apikey}");

            TextToSpeechService service = new TextToSpeechService(authenticator);

            service.SetServiceUrl("{serviceUrl}");

            var words = new List <Word>()
            {
                new Word()
                {
                    _Word       = "EEE",
                    Translation = "<phoneme alphabet=\"ibm\" ph=\"tr1Ipxl.1i\"></phoneme>"
                },
                new Word()
                {
                    _Word       = "IEEE",
                    Translation = "<phoneme alphabet=\"ibm\" ph=\"1Y.tr1Ipxl.1i\"></phoneme>"
                }
            };

            var result = service.AddWords(
                customizationId: "{customizationId}",
                words: words
                );

            Console.WriteLine(result.StatusCode);
        }
Esempio n. 10
0
        public void Synthesize()
        {
            IamConfig config = new IamConfig(
                apikey: apikey
                );

            TextToSpeechService service = new TextToSpeechService(config);

            service.SetEndpoint(url);

            var result = service.Synthesize(
                text: "Hello, welcome to the Watson dotnet SDK!",
                accept: "audio/wav",
                voice: "en-US_AllisonVoice"
                );

            //  Save file
            using (FileStream fs = File.Create("synthesize.wav"))
            {
                result.Result.WriteTo(fs);
                fs.Close();
                result.Result.Close();
            }

            Console.WriteLine(result.Result);
        }
Esempio n. 11
0
    private IEnumerator CreateService()
    {
        if (string.IsNullOrEmpty(_iamApikey))
        {
            throw new IBMException("Plesae provide IAM ApiKey for the service.");
        }

        //  Create credential and instantiate service
        Credentials credentials = null;

        //  Authenticate using iamApikey
        TokenOptions tokenOptions = new TokenOptions()
        {
            IamApiKey = _iamApikey
        };

        credentials = new Credentials(tokenOptions, _serviceUrl);

        //  Wait for tokendata
        while (!credentials.HasIamTokenData())
        {
            yield return(null);
        }

        service = new TextToSpeechService(credentials);
        isReady = true;
    }
Esempio n. 12
0
        public void Synthesize_Success()
        {
            IClient  client  = Substitute.For <IClient>();
            IRequest request = Substitute.For <IRequest>();

            client.PostAsync(Arg.Any <string>())
            .Returns(request);

            TextToSpeechService service = new TextToSpeechService(client);

            var text            = "text";
            var accept          = "accept";
            var voice           = "voice";
            var customizationId = "customizationId";

            var result = service.Synthesize(text: text, accept: accept, voice: voice, customizationId: customizationId);

            JObject bodyObject = new JObject();

            if (!string.IsNullOrEmpty(text))
            {
                bodyObject["text"] = JToken.FromObject(text);
            }
            var json = JsonConvert.SerializeObject(bodyObject);

            request.Received().WithBodyContent(Arg.Is <StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
        }
Esempio n. 13
0
        public void AddWords_Success()
        {
            IClient  client  = Substitute.For <IClient>();
            IRequest request = Substitute.For <IRequest>();

            client.PostAsync(Arg.Any <string>())
            .Returns(request);

            TextToSpeechService service = new TextToSpeechService(client);

            var customizationId = "customizationId";
            var words           = new List <Word>();

            var result = service.AddWords(customizationId: customizationId, words: words);

            JObject bodyObject = new JObject();

            if (words != null && words.Count > 0)
            {
                bodyObject["words"] = JToken.FromObject(words);
            }
            var json = JsonConvert.SerializeObject(bodyObject);

            request.Received().WithBodyContent(Arg.Is <StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
            client.Received().PostAsync($"{service.ServiceUrl}/v1/customizations/{customizationId}/words");
        }
Esempio n. 14
0
        public ReservationDialog(
            IStatePropertyAccessor <ReservationData> userProfileStateAccessor,
            TextToSpeechService ttsService)
            : base(nameof(ReservationDialog))
        {
            UserProfileAccessor = userProfileStateAccessor ?? throw new ArgumentNullException(nameof(userProfileStateAccessor));

            _ttsService = ttsService;
            var waterfallSteps = new WaterfallStep[]
            {
                InitializeStateStepAsync,
                TimeStepAsync,
                AmountPeopleStepAsync,
                NameStepAsync,
                ConfirmationStepAsync,
                FinalStepAsync,
            };

            // Add control flow dialogs
            AddDialog(new WaterfallDialog(ProfileDialog, waterfallSteps));
            AddDialog(new TextPrompt(TimePrompt));
            AddDialog(new TextPrompt(AmountPeoplePrompt, AmountPeopleValidatorAsync));
            AddDialog(new TextPrompt(NamePrompt));
            AddDialog(new ConfirmPrompt(ConfirmationPrompt));
        }
Esempio n. 15
0
        public void Synthesize()
        {
            TokenOptions tokenOptions = new TokenOptions()
            {
                IamApiKey  = apikey,
                ServiceUrl = url
            };

            TextToSpeechService service = new TextToSpeechService(tokenOptions);

            var result = service.Synthesize(
                text: "Hello, welcome to the Watson dotnet SDK!",
                accept: "audio/wav",
                voice: "en-US_AllisonVoice"
                );

            //  Save file
            using (FileStream fs = File.Create("synthesize.wav"))
            {
                result.Result.WriteTo(fs);
                fs.Close();
                result.Result.Close();
            }

            Console.WriteLine(result.Result);
        }
Esempio n. 16
0
        public void AddWord_Success()
        {
            IClient  client  = Substitute.For <IClient>();
            IRequest request = Substitute.For <IRequest>();

            client.PutAsync(Arg.Any <string>())
            .Returns(request);

            TextToSpeechService service = new TextToSpeechService(client);

            var customizationId = "customizationId";
            var word            = "word";
            var translation     = "translation";
            var partOfSpeech    = "partOfSpeech";

            var result = service.AddWord(customizationId: customizationId, word: word, translation: translation, partOfSpeech: partOfSpeech);

            JObject bodyObject = new JObject();

            if (!string.IsNullOrEmpty(translation))
            {
                bodyObject["translation"] = JToken.FromObject(translation);
            }
            if (!string.IsNullOrEmpty(partOfSpeech))
            {
                bodyObject["part_of_speech"] = JToken.FromObject(partOfSpeech);
            }
            var json = JsonConvert.SerializeObject(bodyObject);

            request.Received().WithBodyContent(Arg.Is <StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
            client.Received().PutAsync($"{service.ServiceUrl}/v1/customizations/{customizationId}/words/{word}");
        }
        public void UpdateVoiceModel()
        {
            IamAuthenticator authenticator = new IamAuthenticator(
                apikey: "{apikey}");

            TextToSpeechService service = new TextToSpeechService(authenticator);

            service.SetServiceUrl("{serviceUrl}");

            var words = new List <Word>()
            {
                new Word()
                {
                    _Word       = "NCAA",
                    Translation = "N C double A"
                },
                new Word()
                {
                    _Word       = "iPhone",
                    Translation = "I phone"
                }
            };

            var result = service.UpdateCustomModel(
                customizationId: "{customizationId}",
                name: "First Model Update",
                description: "First custom voice model update",
                words: words
                );

            Console.WriteLine(result.Result);
        }
Esempio n. 18
0
        public void CreateVoiceModel_Success()
        {
            IClient  client  = Substitute.For <IClient>();
            IRequest request = Substitute.For <IRequest>();

            client.PostAsync(Arg.Any <string>())
            .Returns(request);

            TextToSpeechService service = new TextToSpeechService(client);

            var name        = "name";
            var language    = "language";
            var description = "description";

            var result = service.CreateCustomModel(name: name, language: language, description: description);

            JObject bodyObject = new JObject();

            if (!string.IsNullOrEmpty(name))
            {
                bodyObject["name"] = JToken.FromObject(name);
            }
            if (!string.IsNullOrEmpty(language))
            {
                bodyObject["language"] = JToken.FromObject(language);
            }
            if (!string.IsNullOrEmpty(description))
            {
                bodyObject["description"] = JToken.FromObject(description);
            }
            var json = JsonConvert.SerializeObject(bodyObject);

            request.Received().WithBodyContent(Arg.Is <StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
        }
Esempio n. 19
0
 /// <summary>
 /// Sends a text.
 /// </summary>
 /// <param name="msg">The text.</param>
 /// <param name="context">The bot context.</param>
 /// <returns>The response of the bot framework.</returns>
 public virtual async Task <ResourceResponse> SendMessage(string msg, ITurnContext ctx)
 {
     if (_ttsLanguage == null)
     {
         return(await ctx.SendActivityAsync(msg));
     }
     return(await ctx.SendActivityAsync(msg, TextToSpeechService.GenerateSsml(CleanupTextForSpeech(msg), _ttsLanguage)));
 }
        public async Task <string> InputTextAndReturnSoundFile(TextInput input)
        {
            var text = input.Text;
            var textToSpeechService = new TextToSpeechService();
            var uri = await textToSpeechService.GenerateAudioSpeech(text);

            return(uri);
        }
Esempio n. 21
0
        private static void Main(string[] args)
        {
            string credentials = string.Empty;

            #region Get Credentials
            string _endpoint = string.Empty;
            string _username = string.Empty;
            string _password = string.Empty;

            if (string.IsNullOrEmpty(credentials))
            {
                var    parentDirectory     = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.Parent.Parent.FullName;
                string credentialsFilepath = parentDirectory + Path.DirectorySeparatorChar + "sdk-credentials" + Path.DirectorySeparatorChar + "credentials.json";
                if (File.Exists(credentialsFilepath))
                {
                    try
                    {
                        credentials = File.ReadAllText(credentialsFilepath);
                        credentials = Utility.AddTopLevelObjectToJson(credentials, "VCAP_SERVICES");
                    }
                    catch (Exception e)
                    {
                        throw new Exception(string.Format("Failed to load credentials: {0}", e.Message));
                    }

                    VcapCredentials vcapCredentials = JsonConvert.DeserializeObject <VcapCredentials>(credentials);
                    var             vcapServices    = JObject.Parse(credentials);

                    Credential credential = vcapCredentials.GetCredentialByname("text-to-speech-sdk")[0].Credentials;
                    _endpoint = credential.Url;
                    _username = credential.Username;
                    _password = credential.Password;
                }
                else
                {
                    Console.WriteLine("Credentials file does not exist. Please define credentials.");
                    _username = "";
                    _password = "";
                    _endpoint = "";
                }
            }
            #endregion

            string _synthesizeText = "Hello, welcome to the Watson dotnet SDK!";

            Text synthesizeText = new Text
            {
                _Text = _synthesizeText
            };

            var _service = new TextToSpeechService(_username, _password);
            _service.SetEndpoint(_endpoint);

            // MemoryStream Result with .wav data
            var synthesizeResult = _service.Synthesize(synthesizeText, "audio/wav");
            Console.ReadKey();
        }
Esempio n. 22
0
        public void ConstructorExternalConfig()
        {
            var apikey = System.Environment.GetEnvironmentVariable("TEXT_TO_SPEECH_APIKEY");

            System.Environment.SetEnvironmentVariable("TEXT_TO_SPEECH_APIKEY", "apikey");
            TextToSpeechService service = Substitute.For <TextToSpeechService>();

            Assert.IsNotNull(service);
            System.Environment.SetEnvironmentVariable("TEXT_TO_SPEECH_APIKEY", apikey);
        }
Esempio n. 23
0
        protected override void OnAppearingAnimationEnd()
        {
            base.OnAppearingAnimationEnd();

            if (tts != null)
            {
                return;
            }
            tts = DependencyService.Get <TextToSpeechService>(DependencyFetchTarget.NewInstance);
            AtomDevice.Instance.RunOnUIThread(() => OnTapped());
        }
Esempio n. 24
0
        protected async override Task OnAppearingAnimationEnd()
        {
            await base.OnAppearingAnimationEnd();

            if (tts != null)
            {
                return;
            }
            tts = DependencyService.Get <TextToSpeechService>(DependencyFetchTarget.NewInstance);
            await OnTapped();
        }
Esempio n. 25
0
        public async Task <TextAndAudioWrapper> InputQuestionAndReturnAnswer(TextInput textInput)
        {
            var luisService = new LuisService();
            var wrapper     = new TextAndAudioWrapper();
            var question    = textInput.Text;

            var generalKB = new QnAMakerService(_qnaHostName,
                                                "d282ad63-9701-4548-afac-a421f0ec43ed", _endPointKey);

            var groupKB = new QnAMakerService(_qnaHostName,
                                              "b51f7e68-706b-42e4-8b31-0dd34d392a54", _endPointKey);

            var postKB = new QnAMakerService(_qnaHostName,
                                             "92e0fe0c-8826-4e60-8c47-9a4d36cb629e", _endPointKey);


            var intent = await luisService.GetIntent(question);

            string answer;

            switch (intent)
            {
            case "Group":
                answer = await groupKB.GetAnswer(question);

                break;

            case "Post":
                answer = await postKB.GetAnswer(question);

                break;

            case "None":
                answer = await generalKB.GetAnswer(question);

                break;

            default:
                answer = "Sorry, I don't know that.";
                break;
            }

            if (answer == "")
            {
                answer = "Sorry, I don't know that.";
            }

            var textToSpeechService = new TextToSpeechService();
            var audioAnswer         = await textToSpeechService.GenerateAudioSpeech(answer);

            wrapper.Text  = answer;
            wrapper.Audio = audioAnswer;
            return(wrapper);
        }
Esempio n. 26
0
        public EchoBot(IOptions <MySettings> config)
        {
            _dialogs = new DialogSet();
            _dialogs.Add(PromptStep.TimePrompt, new TextPrompt());
            _dialogs.Add(PromptStep.AmountPeoplePrompt, new TextPrompt(AmountPeopleValidator));
            _dialogs.Add(PromptStep.NamePrompt, new TextPrompt());
            _dialogs.Add(PromptStep.ConfirmationPrompt, new ConfirmPrompt(Culture.English));
            _dialogs.Add(PromptStep.GatherInfo, new WaterfallStep[] { TimeStep, AmountPeopleStep, NameStep, ConfirmationStep, FinalStep });

            _ttsService = new TextToSpeechService(config.Value.VoiceFontName, config.Value.VoiceFontLanguage);
        }
Esempio n. 27
0
        public IEnumerator UnityTestSetup()
        {
            if (service == null)
            {
                service = new TextToSpeechService();
            }

            while (!service.Credentials.HasIamTokenData())
            {
                yield return(null);
            }
        }
Esempio n. 28
0
 public MoviePageViewModel()
 {
     TextToSpeechCommand = new Command <string>(text =>
     {
         var speech = TextToSpeechService.Create();
         speech.Speak(text);
     });
     MessagingCenter.Subscribe <DetailPageViewModel, Movie>(this, "SelectedMovie", (model, movie) =>
     {
         Movie = movie;
     });
 }
Esempio n. 29
0
        public ReservationDialog(
            IStatePropertyAccessor <ReservationData> userProfileStateAccessor,
            TextToSpeechService ttsService)
        {
            UserProfileAccessor = userProfileStateAccessor ?? throw new ArgumentNullException(nameof(userProfileStateAccessor));

            _ttsService = ttsService;

            // Add control flow dialogs

            // Add control flow dialogs
        }
        public IEnumerator UnityTestSetup()
        {
            if (service == null)
            {
                service = new TextToSpeechService();
            }

            while (!service.Authenticator.CanAuthenticate())
            {
                yield return(null);
            }
        }