コード例 #1
0
        private void sendSpeakRequest()
        {
            string accessToken;

            // Note: The way to get api key:
            // Free: https://www.microsoft.com/cognitive-services/en-us/subscriptions?productId=/products/Bing.Speech.Preview
            // Paid: https://portal.azure.com/#create/Microsoft.CognitiveServices/apitype/Bing.Speech/pricingtier/S0
            Authentication auth = new Authentication(apiKey);

            try
            {
                accessToken = auth.GetAccessToken();
                //EZBManager.Log("Token: {0}\n", accessToken);
            }
            catch (Exception ex)
            {
                EZBManager.Log("Failed authentication.");
                EZBManager.Log(ex.ToString());
                EZBManager.Log(ex.Message);
                return;
            }

            string requestUri = "https://speech.platform.bing.com/synthesize";

            var speaker = new Synthesize();

            speaker.OnAudioAvailable += PlayAudio;
            speaker.OnError          += ErrorHandler;

            Task task = speaker.Speak(CancellationToken.None, new Synthesize.InputOptions()
            {
                RequestUri = new Uri(requestUri),

                Text = EZ_Builder.Scripting.VariableManager.GetVariable("$textToSpeak"),

                VoiceName = Convert.ToString(_cf.STORAGE[ConfigurationDictionary.VOICE]),

                OutputFormat       = AudioOutputFormat.Riff16Khz16BitMonoPcm,
                AuthorizationToken = "Bearer " + accessToken,
            });

            task.Wait();
        }
コード例 #2
0
        private void PlayAudio(object sender, GenericEventArgs <Stream> args)
        {
            if (Convert.ToBoolean(_cf.STORAGE[ConfigurationDictionary.PLAY_THROUGH_EZB]))
            {
                using (var memoryStream = new MemoryStream())
                {
                    args.EventData.CopyTo(memoryStream);
                    memoryStream.Position = 0;

                    try
                    {
                        using (NAudio.Wave.WaveStream wav = new NAudio.Wave.WaveFileReader(memoryStream))
                        {
                            using (NAudio.Wave.WaveFormatConversionStream pcm = new NAudio.Wave.WaveFormatConversionStream(new NAudio.Wave.WaveFormat(EZ_B.EZBv4Sound.AUDIO_SAMPLE_BITRATE, 8, 1), wav))
                            {
                                if (EZBManager.EZBs[0].SoundV4.IsPlaying)
                                {
                                    stopPlaying();
                                }
                                else
                                {
                                    EZBManager.EZBs[0].SoundV4.PlayData(pcm);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        EZBManager.Log("Error: " + ex.Message);
                        EZBManager.Log("StackTrace: " + ex.StackTrace);
                    }
                }
            }
            else
            {
                SoundPlayer player = new SoundPlayer(args.EventData);
                player.PlaySync();
            }

            args.EventData.Dispose();
        }
 private void OnTokenExpiredCallback(object stateInfo)
 {
     try
     {
         RenewAccessToken();
     }
     catch (Exception ex)
     {
         EZBManager.Log(string.Format("Failed renewing access token. Details: {0}", ex.Message));
     }
     finally
     {
         try
         {
             accessTokenRenewer.Change(TimeSpan.FromMinutes(RefreshTokenDuration), TimeSpan.FromMilliseconds(-1));
         }
         catch (Exception ex)
         {
             EZBManager.Log(string.Format("Failed to reschedule the timer to renew access token. Details: {0}", ex.Message));
         }
     }
 }
コード例 #4
0
 private void ErrorHandler(object sender, GenericEventArgs <Exception> e)
 {
     EZBManager.Log("Unable to complete the TTS request: [{0}]", e.ToString());
 }
        /// <summary>
        /// Sends the specified text to be spoken to the TTS service and saves the response audio to a file.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A Task</returns>
        public Task Speak(CancellationToken cancellationToken, InputOptions inputOptions)
        {
            client.DefaultRequestHeaders.Clear();
            foreach (var header in inputOptions.Headers)
            {
                client.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
            }

            var genderValue = "";

            switch (inputOptions.VoiceType)
            {
            case Gender.Male:
                genderValue = "Male";
                break;

            case Gender.Female:
            default:
                genderValue = "Female";
                break;
            }

            var request = new HttpRequestMessage(HttpMethod.Post, inputOptions.RequestUri)
            {
                Content = new StringContent(GenerateSsml(inputOptions.Locale, genderValue, inputOptions.VoiceName, inputOptions.Text))
            };

            var httpTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
            //EZBManager.Log("Response status code: [{0}]", httpTask.Result.StatusCode);

            var saveTask = httpTask.ContinueWith(
                async(responseMessage, token) =>
            {
                try
                {
                    if (responseMessage.IsCompleted && responseMessage.Result != null && responseMessage.Result.IsSuccessStatusCode)
                    {
                        var httpStream = await responseMessage.Result.Content.ReadAsStreamAsync().ConfigureAwait(false);

                        this.AudioAvailable(new GenericEventArgs <Stream>(httpStream));
                    }
                    else
                    {
                        this.Error(new GenericEventArgs <Exception>(new Exception(String.Format("Service returned {0}", responseMessage.Result.StatusCode))));
                        EZBManager.Log(String.Format("Service returned {0}", responseMessage.Result.StatusCode));
                    }
                }
                catch (Exception e)
                {
                    this.Error(new GenericEventArgs <Exception>(e.GetBaseException()));
                    EZBManager.Log(String.Format("Service returned {0}", responseMessage.Result.StatusCode));
                }
                finally
                {
                    responseMessage.Dispose();
                    request.Dispose();
                }
            },
                TaskContinuationOptions.AttachedToParent,
                cancellationToken);

            return(saveTask);
        }