Beispiel #1
0
        public static async Task SynthesisToSpeakerAsync(string text)
        {
            // Creates an instance of a speech config with specified subscription key and service region.
            // Replace with your own subscription key and service region (e.g., "westus").
            var config = SpeechConfig.FromSubscription("a36c16c465c34906a4deaf107b9fdea6", "uksouth");

            // Creates a speech synthesizer using the default speaker as audio output.
            using (var synthesizer = new SpeechSynthesizer(config))
            {
                text = @"<speak version='1.0' xmlns='https://www.w3.org/2001/10/synthesis' xml:lang='en-US'><voice name='en-GB-MiaNeural'>" + text + "</voice></speak>";
                using (var result = await synthesizer.SpeakSsmlAsync(text))
                //using (var result = await synthesizer.SpeakTextAsync(text))
                {
                    if (result.Reason == ResultReason.Canceled)
                    {
                        var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                        Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");
                        if (cancellation.Reason == CancellationReason.Error)
                        {
                            Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                            Console.WriteLine($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
                            Console.WriteLine($"CANCELED: Did you update the subscription info?");
                        }
                    }
                }
            }
        }
Beispiel #2
0
        /// <summary>
        ///     Based on the Azure SDK example, ensure that speech synthesis was successful
        /// </summary>
        /// <param name="result"></param>
        private bool SpeechWasSynthesized(SpeechSynthesisResult result)
        {
            if (result.Reason == ResultReason.SynthesizingAudioCompleted)
            {
                return(true);
            }

            if (result.Reason == ResultReason.Canceled)
            {
                var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                DebugLogger.LogMessage(LogLevel.Error, Constants.ApplicationName,
                                       $"AzureSpeechModule: CANCELED: Reason={cancellation.Reason}", DateTime.Now);

                if (cancellation.Reason == CancellationReason.Error)
                {
                    DebugLogger.LogMessage(LogLevel.Error, Constants.ApplicationName,
                                           $"AzureSpeechModule: CANCELED: ErrorCode={cancellation.ErrorCode}", DateTime.Now);
                    DebugLogger.LogMessage(LogLevel.Error, Constants.ApplicationName,
                                           $"AzureSpeechModule: CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]", DateTime.Now);
                    DebugLogger.LogMessage(LogLevel.Error, Constants.ApplicationName,
                                           "AzureSpeechModule: CANCELED: Did you update the subscription info?", DateTime.Now);
                }
            }

            return(false);
        }
Beispiel #3
0
        // Speech synthesis events.
        public static async Task SynthesisEventsAsync()
        {
            // Creates an instance of a speech config with specified subscription key and service region.
            // Replace with your own subscription key and service region (e.g., "westus").
            var config = SpeechConfig.FromSubscription("YourSubscriptionKey", "YourServiceRegion");

            // Creates a speech synthesizer with a null output stream.
            // This means the audio output data will not be written to any stream.
            // You can just get the audio from the result.
            using (var synthesizer = new SpeechSynthesizer(config, null))
            {
                // Subscribes to events
                synthesizer.SynthesisStarted += (s, e) =>
                {
                    Console.WriteLine("Synthesis started.");
                };

                synthesizer.Synthesizing += (s, e) =>
                {
                    Console.WriteLine($"Synthesizing event received with audio chunk of {e.Result.AudioData.Length} bytes.");
                };

                synthesizer.SynthesisCompleted += (s, e) =>
                {
                    Console.WriteLine("Synthesis completed.");
                };

                for (int i = 0; i < 2; ++i)
                {
                    // Receives a text from console input and synthesize it to result.
                    Console.WriteLine("Type some text that you want to synthesize...");
                    Console.Write("> ");
                    string text = Console.ReadLine();

                    using (var result = await synthesizer.SpeakTextAsync(text))
                    {
                        if (result.Reason == ResultReason.SynthesizingAudioCompleted)
                        {
                            Console.WriteLine($"Speech synthesized for text [{text}].");
                            var audioData = result.AudioData;
                            Console.WriteLine($"{audioData.Length} bytes of audio data received for text [{text}]");
                        }
                        else if (result.Reason == ResultReason.Canceled)
                        {
                            var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                            Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");

                            if (cancellation.Reason == CancellationReason.Error)
                            {
                                Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                                Console.WriteLine($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
                                Console.WriteLine($"CANCELED: Did you update the subscription info?");
                            }

                            break;
                        }
                    }
                }
            }
        }
        private static async Task Synthesize(string text, SpeechSynthesizer synthesizer)
        {
            using (var r = await synthesizer.SpeakTextAsync(text))
            {
                if (r.Reason == ResultReason.SynthesizingAudioCompleted)
                {
                    Console.WriteLine($"Speech synthesized " +
                                      $"to speaker for text [{text}]");
                }
                else if (r.Reason == ResultReason.Canceled)
                {
                    var cancellation = SpeechSynthesisCancellationDetails.FromResult(r);
                    Console.WriteLine($"CANCELED: " +
                                      $"Reason={cancellation.Reason}");

                    if (cancellation.Reason == CancellationReason.Error)
                    {
                        Console.WriteLine($"Cancelled with " +
                                          $"Error Code {cancellation.ErrorCode}");
                        Console.WriteLine($"Cancelled with " +
                                          $"Error Details " +
                                          $"[{cancellation.ErrorDetails}]");
                    }
                }
            }

            Console.WriteLine("Waiting to play " +
                              "back to the audio...");
            Console.ReadKey();
        }
Beispiel #5
0
        private async Task <byte[]> SynthesisWithByteStreamToByteArrayAsync(string ssmlInput, SpeechConfig config)
        {
            var callback = new PushAudioOutputStreamSampleCallback();

            using var stream       = AudioOutputStream.CreatePushStream(callback);
            using var streamConfig = AudioConfig.FromStreamOutput(stream);
            using var synthesizer  = new SpeechSynthesizer(config, streamConfig);
            using var result       = await synthesizer.SpeakSsmlAsync(ssmlInput);

            if (result.Reason == ResultReason.SynthesizingAudioCompleted)
            {
                return(callback.GetAudioData());
            }
            else if (result.Reason == ResultReason.Canceled)
            {
                var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");

                if (cancellation.Reason == CancellationReason.Error)
                {
                    Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                    Console.WriteLine($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
                    Console.WriteLine($"CANCELED: Did you update the subscription info?");
                }
            }
            return(null);
        }
Beispiel #6
0
        private async void TTSBut_Click(object sender, RoutedEventArgs e)
        {
            var referenceText = StringFromRichTextBox(ReferenceText);

            if (string.IsNullOrWhiteSpace(referenceText))
            {
                MessageBox.Show("Reference text shouldn't be empty.");
                return;
            }

            if (string.IsNullOrWhiteSpace(this.SubscriptionKey.Text))
            {
                MessageBox.Show($"Please provide a valid subscription key for {this.Region.Text} region.");
                return;
            }

            var config = SpeechConfig.FromSubscription(this.SubscriptionKey.Text, this.Region.Text);

            using (var synthesizer = new SpeechSynthesizer(config))
            {
                using (var result = await synthesizer.SpeakTextAsync(referenceText))
                {
                    if (result.Reason == ResultReason.Canceled)
                    {
                        var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                        if (cancellation.Reason == CancellationReason.Error)
                        {
                            MessageBox.Show($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
                        }
                    }
                }
            }
        }
Beispiel #7
0
        public static async Task SynthesisToAudioFileAsync(string key, string region, string forenignText)
        {
            var config = SpeechConfig.FromSubscription(key, region);

            var fileName = "helloworld.wav";

            using (var fileOutput = AudioConfig.FromWavFileOutput(fileName))
            {
                using (var synthesizer = new SpeechSynthesizer(config, fileOutput))
                {
                    var text   = forenignText;
                    var result = await synthesizer.SpeakTextAsync(text);

                    if (result.Reason == ResultReason.SynthesizingAudioCompleted)
                    {
                        Console.WriteLine($"Speech synthesized to [{fileName}] for text [{text}]");
                    }
                    else if (result.Reason == ResultReason.Canceled)
                    {
                        var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                        Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");

                        if (cancellation.Reason == CancellationReason.Error)
                        {
                            Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                            Console.WriteLine($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
                            Console.WriteLine($"CANCELED: Did you update the subscription info?");
                        }
                    }
                }
            }
        }
        private async void TTSBut_Click(object sender, RoutedEventArgs e)
        {
            //if (string.IsNullOrWhiteSpace(referenceText)) {
            //    referenceText = StringFromRichTextBox(ReferenceText);
            //}
            if (string.IsNullOrWhiteSpace(referenceText))
            {
                return;
            }
            var config = SpeechConfig.FromSubscription(subscriptionKey, region);

            //config.SpeechSynthesisVoiceName = "zh-TW-Yating-Apollo";

            using (var synthesizer = new SpeechSynthesizer(config))
            {
                using (var result = await synthesizer.SpeakTextAsync(referenceText))
                {
                    if (result.Reason == ResultReason.Canceled)
                    {
                        var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                        MessageBox.Show($"CANCELED: Reason={cancellation.Reason}");

                        if (cancellation.Reason == CancellationReason.Error)
                        {
                            MessageBox.Show($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
                        }
                    }
                }
            }
        }
        private async void OnReadButtonClicked(object sender, EventArgs e)
        {
            try {
                var config = SpeechConfig.FromSubscription(speech_key, "westus");
                config.SpeechSynthesisLanguage = viewModel.LangCodeDictionary
                                                 [(string)TargetLanguage.SelectedItem];

                using (var synthesizer = new SpeechSynthesizer(config)){
                    StringBuilder sb = new StringBuilder();
                    using (var result = await synthesizer.SpeakTextAsync(TranslatedText.Text))
                        if (result.Reason == ResultReason.SynthesizingAudioCompleted)
                        {
                            sb.Append($"Speech synthesized to speaker for text [{RecognitionText.Text}]");
                        }
                        else if (result.Reason == ResultReason.Canceled)
                        {
                            var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                            sb.Append($"CANCELED: Reason={cancellation.Reason}");

                            if (cancellation.Reason == CancellationReason.Error)
                            {
                                sb.Append($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                                sb.Append($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
                                sb.Append($"CANCELED: Did you update the subscription info?");
                            }
                        }
                }
            }
            catch (Exception ex)
            {
                UpdateUI(ex.Message);
            }
        }
    public void Speech(string text)
    {
        using (var synthsizer = new SpeechSynthesizer(speechConfig, null))
        {
            // Starts speech synthesis, and returns after a single utterance is synthesized.
            var result = synthsizer.SpeakTextAsync(text).Result;

            // Checks result.
            string newMessage = string.Empty;
            if (result.Reason == ResultReason.SynthesizingAudioCompleted)
            {
                var audioClip = ByteArrayToClip(result.AudioData);
                audioSource.clip = audioClip;

                Invoke("AudioEnd", audioClip.length);

                audioSource.Play();

                Debug.Log("Speech synthesis succeeded!");
            }
            else if (result.Reason == ResultReason.Canceled)
            {
                var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                Debug.Log($"CANCELED:\nReason=[{cancellation.Reason}]\nErrorDetails=[{cancellation.ErrorDetails}]\nDid you update the subscription info?");
            }
        }
    }
Beispiel #11
0
        public static async Task SynthesisToAudioFileAsync()
        {
            var config   = SpeechConfig.FromSubscription("b7f8752c5aaf46729b1dd7eb05851559", "westus");
            var fileName = "helloworld.wav";

            using (var fileOutput = AudioConfig.FromWavFileOutput(fileName))
            {
                using (var synthesizer = new SpeechSynthesizer(config))
                {
                    var text   = "Hello world!";
                    var result = await synthesizer.SpeakTextAsync(text);

                    if (result.Reason == ResultReason.SynthesizingAudioCompleted)
                    {
                        Console.WriteLine($"Speech synthesized for text [{text}]");
                    }
                    else if (result.Reason == ResultReason.Canceled)
                    {
                        var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                        Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");

                        if (cancellation.Reason == CancellationReason.Error)
                        {
                            Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                            Console.WriteLine($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
                            Console.WriteLine($"CANCELED: Did you update the subscription info?");
                        }
                    }
                }
            }
        }
Beispiel #12
0
        public async Task SaySomethingNice(string message)
        {
            logger.LogInformation($"Saying: {message}");

            using (var result = await speechSynthesizer.SpeakTextAsync(message))
            {
                if (result.Reason == ResultReason.SynthesizingAudioCompleted)
                {
                    logger.LogInformation($"Speech synthesized to speaker for text [{message}]");
                }
                else if (result.Reason == ResultReason.Canceled)
                {
                    var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                    logger.LogInformation($"CANCELED: Reason={cancellation.Reason}");

                    if (cancellation.Reason == CancellationReason.Error)
                    {
                        logger.LogError($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                        logger.LogError($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
                        logger.LogError($"CANCELED: Did you update the subscription info?");
                    }
                }
            }
            return;
        }
Beispiel #13
0
        public async Task CovertTextToSpeechFromMicrophone(string TextToSpeek)
        {
            SpeechConfig config = SpeechConfig.FromSubscription(Subscription.key, Subscription.region);

            // Creates a speech synthesizer using the default speaker as audio output.
            using (var synthesizer = new SpeechSynthesizer(config))
            {
                // Receive a text from console input and synthesize it to speaker.

                using (var result = await synthesizer.SpeakTextAsync(TextToSpeek))
                {
                    if (result.Reason == ResultReason.SynthesizingAudioCompleted)
                    {
                        Console.WriteLine($"Voice Bot Assistance said :  [{TextToSpeek}]");
                    }
                    else if (result.Reason == ResultReason.Canceled)
                    {
                        var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                        Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");

                        if (cancellation.Reason == CancellationReason.Error)
                        {
                            Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                            Console.WriteLine($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
                            Console.WriteLine($"CANCELED: Did you update the subscription info?");
                        }
                    }
                }

                // This is to give some time for the speaker to finish playing back the audio
                //Console.WriteLine("Press any key to exit...");
                //Console.ReadKey();
            }
        }
Beispiel #14
0
        public static async Task SynthesisToSpeakerAsync()
        {
            var config = SpeechConfig.FromSubscription("YOUR_API_KEY", "YOUR_LOCATION");

            config.SpeechSynthesisLanguage = "ja-JP";

            // Creates a speech synthesizer using the default speaker as audio output.
            using (var synthesizer = new SpeechSynthesizer(config))
            {
                // Receive a text from console input and synthesize it to speaker.
                Console.WriteLine("Type some text that you want to speak...");
                Console.Write("> ");
                string text = Console.ReadLine();

                using (var result = await synthesizer.SpeakTextAsync(text))
                {
                    if (result.Reason == ResultReason.SynthesizingAudioCompleted)
                    {
                        Console.WriteLine($"Speech synthesized to speaker for text [{text}]");
                    }
                    else if (result.Reason == ResultReason.Canceled)
                    {
                        var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                        Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");

                        if (cancellation.Reason == CancellationReason.Error)
                        {
                            Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                            Console.WriteLine($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
                            Console.WriteLine($"CANCELED: Did you update the subscription info?");
                        }
                    }
                }
            }
        }
        public void SpeakTextAsync(string speechLanguage, string textToSynthesize)
        {
            if (Monitor.TryEnter(locker))
            {
                try
                {
                    var result = speechToText.SpeakTextAsync(speechLanguage, textToSynthesize).Result;

                    if (result.Reason == ResultReason.SynthesizingAudioCompleted)
                    {
                        Console.WriteLine($"Speech synthesized to speaker for text [{textToSynthesize}]");
                    }
                    else if (result.Reason == ResultReason.Canceled)
                    {
                        var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                        Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");

                        if (cancellation.Reason == CancellationReason.Error)
                        {
                            Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                            Console.WriteLine($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
                            Console.WriteLine($"CANCELED: Did you update the subscription info?");
                        }
                    }
                }
                finally
                {
                    Monitor.Exit(locker);
                }
            }
        }
        public static async Task SynthesisToSpeakerAsync()
        {
            var config = SpeechConfig.FromSubscription("8afdd1b2184d4cb794b264fafba98868", "eastus");

            using (var synthesizer = new SpeechSynthesizer(config))
            {
                string text = (Story_Overview.StoryOverview());
                using (var result = await synthesizer.SpeakTextAsync(text))
                {
                    if (result.Reason == ResultReason.SynthesizingAudioCompleted)
                    {
                        Console.WriteLine($"Speech synthesized to speaker for text [{text}]");
                    }

                    else if (result.Reason == ResultReason.Canceled)
                    {
                        var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                        Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");

                        if (cancellation.Reason == CancellationReason.Error)
                        {
                            Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                            Console.WriteLine($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
                            Console.WriteLine($"CANCELED: Did you update the subscription info?");
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Method to convert text to speech wav file
        /// </summary>
        /// <param name="inuptext"></param>
        /// <param name="wavfilename"></param>
        /// <returns></returns>
        public static async Task SynthesisToWaveFileAsync(string inuptext, string wavfilename)
        {
            // Creates an instance of a speech config with specified subscription key and service region.
            // Replace with your own subscription key and service region (e.g., "westus").
            // The default language is "en-us".
            var config = SpeechConfig.FromSubscription(SubscriptionKey, ServiceRegion);

            // Creates a speech synthesizer using file as audio output.
            // Replace with your own audio file name.
            var fileName = wavfilename;

            using (var fileOutput = AudioConfig.FromWavFileOutput(fileName))
                using (var synthesizer = new SpeechSynthesizer(config, fileOutput))
                {
                    using (var result = await synthesizer.SpeakTextAsync(inuptext))
                    {
                        if (result.Reason == ResultReason.SynthesizingAudioCompleted)
                        {
                            Console.WriteLine($"Speech synthesized for text [{inuptext}], and the audio was saved to [{fileName}]");
                        }
                        else if (result.Reason == ResultReason.Canceled)
                        {
                            var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                            Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");

                            if (cancellation.Reason == CancellationReason.Error)
                            {
                                Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                                Console.WriteLine($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
                                Console.WriteLine($"CANCELED: Did you update the subscription info?");
                            }
                        }
                    }
                }
        }
Beispiel #18
0
        public async Task SynthesisToSpeakerAsync(string actor, string actorWords)
        {
            var config = SpeechConfig.FromSubscription(key, "westus2");

            config.SpeechSynthesisVoiceName = voiceBank[actor]; //Voice options available at: https://docs.microsoft.com/en-us/azure/cognitive-services/speech-service/language-support#text-to-speech
            // Creates a speech synthesizer using the default speaker as audio output.
            using (var synthesizer = new SpeechSynthesizer(config))
            {
                // Receive a text from console input and synthesize it to speaker.


                using (var result = await synthesizer.SpeakTextAsync(actorWords))
                {
                    if (result.Reason == ResultReason.SynthesizingAudioCompleted)
                    {
                    }
                    else if (result.Reason == ResultReason.Canceled)
                    {
                        var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);

                        if (cancellation.Reason == CancellationReason.Error)
                        {
                        }
                    }
                }
            }
        }
Beispiel #19
0
        public async static Task SaveTheWavOrMp3()
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            string filterStr = "";

            if (_LV.mp3Selected)
            {
                filterStr = "Supported Audio |*.mp3";
            }
            else
            {
                filterStr = "Supported Audio |*.wav";
            }

            saveFileDialog.Filter = filterStr;
            if (saveFileDialog.ShowDialog() == true)
            {
                // File.WriteAllText(saveFileDialog.FileName, txtEditor.Text);
                var config = SpeechConfig.FromSubscription(_LV.subscriptionKey, _LV.serviceRegion);

                // Creates a speech synthesizer using file as audio output.
                // Replace with your own audio file name.
                var fileName = saveFileDialog.FileName;

                using (var fileOutput = AudioConfig.FromWavFileOutput(fileName))
                {
                    using (var synthesizer = new SpeechSynthesizer(config, fileOutput))
                    {
                        while (true)
                        {
                            // Receives a text from console input and synthesize it to wave file.
                            string text = _LV.getInputText_Voice;
                            if (string.IsNullOrEmpty(text))
                            {
                                break;
                            }

                            using (var result = await synthesizer.SpeakSsmlAsync(text))
                            {
                                if (result.Reason == ResultReason.SynthesizingAudioCompleted)
                                {
                                    _LV.OutputText = $"Speech synthesized for text, and the audio was saved to [{fileName}]";
                                }
                                else if (result.Reason == ResultReason.Canceled)
                                {
                                    var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                                    _LV.OutputText = $"CANCELED: Reason={cancellation.Reason}";

                                    if (cancellation.Reason == CancellationReason.Error)
                                    {
                                        _LV.OutputText = $"CANCELED: ErrorCode={cancellation.ErrorCode}" + $"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]";
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        public static async Task SynthesisToSpeakerAsync(string input)
        {
            // Creates an instance of a speech config with specified subscription key and service region.
            // Replace with your own subscription key and service region (e.g., "westus").
            // The default language is "en-us".
            //var config = SpeechConfig.FromSubscription("8f106f3d80ec434fa7accc2e0a912c48", "northeurope");

            // Creates a speech synthesizer using the default speaker as audio output.
            {
                using (var result = await synthesizer.SpeakTextAsync(input))
                {
                    if (result.Reason == ResultReason.SynthesizingAudioCompleted)
                    {
                    }
                    else if (result.Reason == ResultReason.Canceled)
                    {
                        var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);

                        if (cancellation.Reason == CancellationReason.Error)
                        {
                            //TODO HANDLE ERROR?
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 判斷回傳執行結果狀態
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        private bool CheckReason(dynamic result)
        {
            // 發生錯誤
            if (result.Reason == ResultReason.Canceled)
            {
                var typeName = result.GetType().Name;

                // 發生錯誤,提示訊息
                if (typeName == "RecognitionResult")
                {
                    this.DisPlayMessage(CancellationDetails.FromResult(result));
                }

                if (typeName == "SpeechSynthesisResult")
                {
                    this.DisPlayMessage(SpeechSynthesisCancellationDetails.FromResult(result));
                }
            }

            // 如果 執行結果為 語音轉文字類型
            // 設定 辨識後的文字
            if (result as RecognitionResult != null)
            {
                recognizeText = result.Text;
            }

            // 無法辨識輸入結果
            if (result.Reason == ResultReason.NoMatch)
            {
                recognizeText = $"無法辨識輸入語音,請重新輸入\n";
            }

            return(true);
        }
Beispiel #22
0
        private async Task <bool> TextToWavFileAsync(string text, string pathToFile)
        {
            using var audioConfig = AudioConfig.FromWavFileOutput(pathToFile);
            using var synthesizer = new SpeechSynthesizer(_config, audioConfig);
            var result = await synthesizer.SpeakTextAsync(text);

            if (result.Reason == ResultReason.SynthesizingAudioCompleted)
            {
                _logger.LogInformation($"Speech synthesized to speaker for text [{text}]");
                return(true);
            }
            else if (result.Reason == ResultReason.Canceled)
            {
                var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                _logger.LogError($"CANCELED: Reason={cancellation.Reason}");

                if (cancellation.Reason == CancellationReason.Error)
                {
                    _logger.LogError($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                    _logger.LogError($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
                }
            }

            return(false);
        }
Beispiel #23
0
        public static async Task SynthesisToAudioFileAsync()
        {
            var config = SpeechConfig.FromSubscription("cdd4859020d94d1ab919ad18e313cab5", "westus2");

            var fileName = "introduction.wav";

            using (var fileOutput = AudioConfig.FromWavFileOutput(fileName))
            {
                using (var synthesizer = new SpeechSynthesizer(config, fileOutput))
                {
                    var text   = "The upload was successful, you find yourself in another C.R.A.I.G.unit that has been abandoned in the forest you have escaped The Syndicate.You realize you are free but now there is nothing... \n\nC.R.A.I.G. : Why...why did I even try?!I'm just a robot! I was programmed to do one thing and only one thing: work!\n\nC.R.A.I.G. : And yet. I am here. I am frustrated. I am lonely. I am. Was all this in my original programming?\n\nC.R.A.I.G. : Even if I find 'love', will it be real...or just a construct of my creators...how will I know?\n\nYou begin to wonder if the effort was worth it. Will you get the answers you are looking for, or will it just lead to more questions?";
                    var result = await synthesizer.SpeakTextAsync(text);

                    if (result.Reason == ResultReason.SynthesizingAudioCompleted)
                    {
                        Console.WriteLine($"Speech synthesized to [{fileName}] for text [{text}]");
                    }
                    else if (result.Reason == ResultReason.Canceled)
                    {
                        var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                        Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");

                        if (cancellation.Reason == CancellationReason.Error)
                        {
                            Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                            Console.WriteLine($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
                            Console.WriteLine($"CANCELED: Did you update the subscription info?");
                        }
                    }
                }
            }
        }
Beispiel #24
0
        public async Task <string> SynthesisToSpeakerAsync(string text)
        {
            var config = GetClient();
            var sb     = new StringBuilder();


            using var synthesizer = new SpeechSynthesizer(config,
                                                          AutoDetectSourceLanguageConfig.FromOpenRange(),
                                                          AudioConfig.FromDefaultSpeakerOutput());

            using var result = await synthesizer.SpeakTextAsync(text);

            if (result.Reason == ResultReason.SynthesizingAudioCompleted)
            {
                sb.AppendLine($"Speech synthesized to speaker for text [{text}]");
            }
            else if (result.Reason == ResultReason.Canceled)
            {
                var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                sb.AppendLine($"CANCELED: Reason={cancellation.Reason}");

                if (cancellation.Reason == CancellationReason.Error)
                {
                    sb.AppendLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                    sb.AppendLine($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
                    sb.AppendLine($"CANCELED: Did you update the subscription info?");
                }
            }
            return(sb.ToString());
        }
Beispiel #25
0
        private async Task <bool> SynthesisToWaveFileAsync(string filename, string ssmlInput, SpeechConfig config)
        {
            using var synthesizer = new SpeechSynthesizer(config, null);
            using var result      = await synthesizer.SpeakSsmlAsync(ssmlInput);

            if (result.Reason == ResultReason.SynthesizingAudioCompleted)
            {
                using var audioDataStream = AudioDataStream.FromResult(result);
                await audioDataStream.SaveToWaveFileAsync(filename);

                return(true);
            }
            else if (result.Reason == ResultReason.Canceled)
            {
                var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");

                if (cancellation.Reason == CancellationReason.Error)
                {
                    Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                    Console.WriteLine($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
                    Console.WriteLine($"CANCELED: Did you update the subscription info?");
                }
            }
            return(false);
        }
Beispiel #26
0
        async void Speak_Button_Clicked(object sender, EventArgs e, string result)
        {
            var config = SpeechConfig.FromSubscription("7de39c59c0774086b8e4bb22bff0df45", "westus");

            string text = result;

            var synthesizer = new SpeechSynthesizer(config);

            using (var result1 = await synthesizer.SpeakTextAsync(text))
            {
                if (result1.Reason == ResultReason.SynthesizingAudioCompleted)
                {
                    Console.WriteLine($"Speech synthesized to speaker for text [{text}]");
                }
                else if (result1.Reason == ResultReason.Canceled)
                {
                    var cancellation = SpeechSynthesisCancellationDetails.FromResult(result1);
                    Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");

                    if (cancellation.Reason == CancellationReason.Error)
                    {
                        Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                        Console.WriteLine($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
                        Console.WriteLine($"CANCELED: Did you update the subscription info?");
                    }
                }
            }
        }
        public override AudioClip SynthesizeText(string text)
        {
            // Starts speech synthesis, and returns after a single utterance is synthesized.

            // todo speak ssml or plain text depending on input.
            var result = _synthesizer.SpeakSsmlAsync(text).Result;

            if (result.Reason == ResultReason.SynthesizingAudioCompleted)
            {
                // Since native playback is not yet supported on Unity yet (currently only supported on Windows/Linux Desktop),
                // use the Unity API to play audio here as a short term solution.
                // Native playback support will be added in the future release.
                var sampleCount = result.AudioData.Length / 2;
                var audioData   = new float[sampleCount];
                for (var i = 0; i < sampleCount; ++i)
                {
                    audioData[i] = (short)(result.AudioData[i * 2 + 1] << 8 | result.AudioData[i * 2]) / 32768.0F;
                }

                // The default output audio format is 16K 16bit mono
                var audioClip = AudioClip.Create("SynthesizedAudio", sampleCount, 1, 16000, false);
                audioClip.SetData(audioData, 0);
                return(audioClip);
            }

            if (result.Reason != ResultReason.Canceled)
            {
                return(null);
            }
            var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);

            Debug.Log(
                $"CANCELED:\nReason=[{cancellation.Reason}]\nErrorDetails=[{cancellation.ErrorDetails}]\nDid you update the subscription info?");
            return(null);
        }
        public static async Task SynthesisToSpeakerAsync()
        {
            // Creates an instance of a speech config with specified subscription key and service region.
            // Replace with your own subscription key and service region (e.g., "westus").
            var config = SpeechConfig.FromSubscription("YourSubscriptionKey", "YourServiceRegion");

            // Creates a speech synthesizer using the default speaker as audio output.
            using (var synthesizer = new SpeechSynthesizer(config))
            {
                // Receive a text from console input and synthesize it to speaker.
                Console.WriteLine("Type some text that you want to speak...");
                Console.Write("> ");
                string text = Console.ReadLine();

                using (var result = await synthesizer.SpeakTextAsync(text))
                {
                    if (result.Reason == ResultReason.SynthesizingAudioCompleted)
                    {
                        Console.WriteLine($"Speech synthesized to speaker for text [{text}]");
                    }
                    else if (result.Reason == ResultReason.Canceled)
                    {
                        var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                        Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");

                        if (cancellation.Reason == CancellationReason.Error)
                        {
                            Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                            Console.WriteLine($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
                            Console.WriteLine($"CANCELED: Did you update the subscription info?");
                        }
                    }
                }
            }
        }
        public async Task <AudioStream> SpeakAsync(string text, Boolean useNeural = false)
        {
            using var synthesizer = new SpeechSynthesizer(_speechConfig, null);
            var ssml = String.Format(SSML_TEMPLATE, text, useNeural ? "zh-CN-XiaoxiaoNeural" : "zh-CN-Yaoyao-Apollo");

            using var result = await synthesizer.SpeakSsmlAsync(ssml);

            if (result.Reason == ResultReason.SynthesizingAudioCompleted)
            {
                return(AudioDataStream.FromResult(result));
            }
            else if (result.Reason == ResultReason.Canceled)
            {
                var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");

                if (cancellation.Reason == CancellationReason.Error)
                {
                    Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                    Console.WriteLine($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
                    Console.WriteLine($"CANCELED: Did you update the subscription info?");
                }
            }
            return(null);
        }
Beispiel #30
0
        // Speech synthesis to pull audio output stream.
        public static async Task SynthesisToPullAudioOutputStreamAsync()
        {
            // Creates an instance of a speech config with specified subscription key and service region.
            // Replace with your own subscription key and service region (e.g., "westus").
            var config = SpeechConfig.FromSubscription("YourSubscriptionKey", "YourServiceRegion");

            // Creates an audio out stream.
            using (var stream = AudioOutputStream.CreatePullStream())
            {
                // Creates a speech synthesizer using audio stream output.
                using (var streamConfig = AudioConfig.FromStreamOutput(stream))
                    using (var synthesizer = new SpeechSynthesizer(config, streamConfig))
                    {
                        while (true)
                        {
                            // Receives a text from console input and synthesize it to pull audio output stream.
                            Console.WriteLine("Enter some text that you want to synthesize, or enter empty text to exit.");
                            Console.Write("> ");
                            string text = Console.ReadLine();
                            if (string.IsNullOrEmpty(text))
                            {
                                break;
                            }

                            using (var result = await synthesizer.SpeakTextAsync(text))
                            {
                                if (result.Reason == ResultReason.SynthesizingAudioCompleted)
                                {
                                    Console.WriteLine($"Speech synthesized for text [{text}], and the audio was written to output stream.");
                                }
                                else if (result.Reason == ResultReason.Canceled)
                                {
                                    var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                                    Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");

                                    if (cancellation.Reason == CancellationReason.Error)
                                    {
                                        Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                                        Console.WriteLine($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
                                        Console.WriteLine($"CANCELED: Did you update the subscription info?");
                                    }
                                }
                            }
                        }
                    }

                // Reads(pulls) data from the stream
                byte[] buffer     = new byte[32000];
                uint   filledSize = 0;
                uint   totalSize  = 0;
                while ((filledSize = stream.Read(buffer)) > 0)
                {
                    Console.WriteLine($"{filledSize} bytes received.");
                    totalSize += filledSize;
                }

                Console.WriteLine($"Totally {totalSize} bytes received.");
            }
        }