/// <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?");
                            }
                        }
                    }
                }
        }
Ejemplo n.º 2
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}]";
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 3
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);
        }
Ejemplo n.º 4
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?");
                        }
                    }
                }
            }
        }
Ejemplo n.º 5
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?");
                        }
                    }
                }
            }
        }
        private static async Task <string> GenerateCustomAudioMessage()
        {
            var key           = ConfigurationManager.AppSettings["CognitiveServiceKey"];
            var region        = ConfigurationManager.AppSettings["CognitiveServiceRegion"];
            var customMessage = ConfigurationManager.AppSettings["CustomMessage"];

            try
            {
                if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(region) && !string.IsNullOrEmpty(customMessage))
                {
                    var config = SpeechConfig.FromSubscription(key, region);
                    config.SetSpeechSynthesisOutputFormat(SpeechSynthesisOutputFormat.Riff16Khz16BitMonoPcm);

                    var audioConfig = AudioConfig.FromWavFileOutput($"../../../audio/custom-message.wav");
                    var synthesizer = new SpeechSynthesizer(config, audioConfig);

                    await synthesizer.SpeakTextAsync(customMessage);

                    return("custom-message.wav");
                }

                return("sample-message.wav");
            }
            catch (Exception ex)
            {
                Logger.LogMessage(Logger.MessageType.ERROR, $"Exception while generating text to speech, falling back to sample audio. Exception: {ex.Message}");
                return("sample-message.wav");
            }
        }
Ejemplo n.º 7
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?");
                        }
                    }
                }
            }
        }
Ejemplo n.º 8
0
        private static async Task SynthesizeSpeechAsync(IConfiguration config, FileInfo textFile)
        {
            var text = await File.ReadAllLinesAsync(textFile.FullName);

            int contineWith = 0;
            int counter     = contineWith;

            foreach (var page in text.Page(25).Skip(contineWith))
            {
                var outputFile = Path.Combine(textFile.DirectoryName, $"{Path.GetFileNameWithoutExtension(textFile.Name)}{counter:D4}.wav");

                Log($"synthesizing page {counter}", ConsoleColor.Gray);

                var speechConfig = SpeechConfig.FromSubscription(config["SubscriptionKey"], config["Region"]);
                using var speech = new SpeechSynthesizer(speechConfig,
                                                         AutoDetectSourceLanguageConfig.FromOpenRange(),
                                                         AudioConfig.FromWavFileOutput(outputFile));

                string textToConvert = string.Join(Environment.NewLine, page);
                var    result        = await speech.SpeakTextAsync(textToConvert);

                if (result.Reason != ResultReason.SynthesizingAudioCompleted)
                {
                    throw new Exception(result.Reason.ToString());
                }

                counter++;
            }
        }
Ejemplo n.º 9
0
        private async Task CreateAndSaveAudioAsync(string textToSay, string filePathToSave, string fileName)
        {
            var config = SpeechConfig.FromSubscription(AppSettings.SpeechService_ApiKey, AppSettings.SpeechServiceRegion);

            using var audioConfig = AudioConfig.FromWavFileOutput($"{filePathToSave}/{fileName}.wav");
            using var synthesizer = new SpeechSynthesizer(config, audioConfig);
            await synthesizer.SpeakTextAsync(textToSay);
        }
Ejemplo n.º 10
0
        /// <summary>文字转语音 输出到文件</summary>
        public static async Task SynthesisToAudioAsync(string inputText, string outputFileName)
        {
            var config = SpeechConfig.FromSubscription(subscriptionKey, region);

            using var audioConfig = AudioConfig.FromWavFileOutput(outputFileName);
            using var synthesizer = new SpeechSynthesizer(config, audioConfig);
            await synthesizer.SpeakTextAsync(inputText);
        }
Ejemplo n.º 11
0
        public async Task TranslateText(string content, string path)
        {
            var config = SpeechConfig.FromSubscription(Options.SubscriptionKey, Options.Region);

            using var audioConfig = AudioConfig.FromWavFileOutput(path);
            using var synthesizer = new SpeechSynthesizer(config, audioConfig);
            await synthesizer.SpeakTextAsync(content);
        }
Ejemplo n.º 12
0
        public static async Task SynthesisToAudioFileAsync(TextToSpeech tts, string azureSubscriptionKey = null, string azureRegion = null)
        {
            if (azureSubscriptionKey == null)
            {
                azureSubscriptionKey = await AzureSubscriptionKey.LoadFromJson();
            }

            if (azureRegion == null)
            {
                azureRegion = Region.USWest.ToString();
            }

            var config = SpeechConfig.FromSubscription(azureSubscriptionKey, azureRegion);

            config.SpeechSynthesisVoiceName = tts.AzureVoice;

            String filename;

            Directory.CreateDirectory(_outputDir);

            foreach (var item in tts.Texts)
            {
                // WAV is the standard format and file extension has to be checked.
                if (string.IsNullOrEmpty(new FileInfo(item.Key).Extension))
                {
                    filename = string.Concat(_outputDir, item.Key, ".wav");
                }
                else
                {
                    filename = string.Concat(_outputDir, item.Key);
                }

                using (var fileOutput = AudioConfig.FromWavFileOutput(filename))
                {
                    using (var synthesizer = new SpeechSynthesizer(config, fileOutput))
                    {
                        var result = await synthesizer.SpeakTextAsync(item.Value);

                        if (result.Reason == ResultReason.SynthesizingAudioCompleted)
                        {
                            Console.WriteLine($"Speech synthesized to [{filename}] for text [{item.Value}]");
                        }
                        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?");
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 13
0
        /// <summary>文字转语音 输出到文件</summary>
        public static async Task SynthesisToAudioMP3Async(string inputText, string outputFileName)
        {
            var config = SpeechConfig.FromSubscription(subscriptionKey, region);

            config.SetSpeechSynthesisOutputFormat(SpeechSynthesisOutputFormat.Audio16Khz32KBitRateMonoMp3);
            using var audioConfig = AudioConfig.FromWavFileOutput(outputFileName);
            using var synthesizer = new SpeechSynthesizer(config, audioConfig);
            await synthesizer.SpeakTextAsync(inputText);
        }
        public static async Task TextToAudioFileAsync(string text, string fn)
        {
            var config = SpeechConfig.FromSubscription(cKey, cRegion);

            using (FileStream f = new FileStream(fn, FileMode.Create))
                using (BinaryWriter wr = new BinaryWriter(f))
                    wr.Write(System.Text.Encoding.ASCII.GetBytes("RIFF"));

            using (var fo = AudioConfig.FromWavFileOutput(fn))
                using (var synthesizer = new SpeechSynthesizer(config, fo))
                    await Synthesize(text, synthesizer);
        }
Ejemplo n.º 15
0
        // Speech synthesis to MP3 file.
        public static async Task SynthesisToMp3FileAsync()
        {
            // 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("YourSubscriptionKey", "YourServiceRegion");

            // Sets the synthesis output format.
            // The full list of supported format can be found here:
            // https://docs.microsoft.com/azure/cognitive-services/speech-service/rest-text-to-speech#audio-outputs
            config.SetSpeechSynthesisOutputFormat(SpeechSynthesisOutputFormat.Audio16Khz32KBitRateMonoMp3);

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

            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 mp3 file.
                        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 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?");
                                }
                            }
                        }
                    }
                }
        }
Ejemplo n.º 16
0
        static async Task <string> SynthesizeAudioAsync(string key, string region, int index, IDictionary <string, object> model, string inputSsml, string outputFolder)
        {
            var config      = SpeechConfig.FromSubscription(key, region);
            var fn          = index.ToString().PadLeft(3, '0');
            var wavFilename = Path.Combine(outputFolder, Path.ChangeExtension(fn, "wav"));

            if (!Directory.Exists(outputFolder))
            {
                Directory.CreateDirectory(outputFolder);
            }

            SpeechSynthesisResult result;
            var bytes = new byte[] { };

            using (var audioConfig = AudioConfig.FromWavFileOutput(wavFilename))
            {
                config.SetSpeechSynthesisOutputFormat(SpeechSynthesisOutputFormat.Riff24Khz16BitMonoPcm);
                using (var synthesizer = new SpeechSynthesizer(config, audioConfig))
                {
                    //Console.WriteLine("doing ");
                    var ssml     = File.ReadAllText(inputSsml);
                    var template = Scriban.Template.Parse(ssml);
                    var content  = template.Render(model);

                    if (string.IsNullOrWhiteSpace(content.Trim('\n')))
                    {
                        return("");
                    }

                    result = await synthesizer.SpeakSsmlAsync(content);

                    //Console.WriteLine("something ");

                    await File.WriteAllTextAsync(Path.Combine(outputFolder, Path.ChangeExtension(fn, "txt")), content);
                }
            }
            var mp3Filename = Path.Combine(outputFolder, Path.ChangeExtension(fn, "mp3"));

            if (result.AudioData.Any())
            {
                using (var ms = new MemoryStream(result.AudioData))
                {
                    ConvertWavStreamToMp3File(ms, mp3Filename);
                    File.Delete(wavFilename);
                }
            }

            return(mp3Filename);
        }
Ejemplo n.º 17
0
    public async Task SynthesisToAudioFileAsync(string temp)
    {
        var config = SpeechConfig.FromSubscription("c5ab91b760b24599b3667791c08aa7d9", "uksouth");

        var fileName = @"Assets/Resources/Audio/Conv" + temp + "Audio.wav";

        using (var fileOutput = AudioConfig.FromWavFileOutput(fileName))
        {
            using (var synthesizer = new SpeechSynthesizer(config, fileOutput))
            {
                StringBuilder sb = new StringBuilder();
                foreach (char c in temp)
                {
                    if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '.')
                    {
                        sb.Append(c);
                    }
                    if (c == '-')
                    {
                        sb.Append(',');
                    }
                }
                temp = sb.ToString();

                var    text   = "Hello world!";
                string ssml   = @"<speak version='1.0' xmlns='https://www.w3.org/2001/10/synthesis' xml:lang='en-US'><voice name='ja-JP-Ayumi-Apollo'>" + temp + "</voice></speak>";
                var    result = await synthesizer.SpeakSsmlAsync(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?");
                    }
                }
            }
        }
    }
Ejemplo n.º 18
0
        // Speech synthesis to wave file.
        public static async Task SynthesisToWaveFileAsync()
        {
            // 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("YourSubscriptionKey", "YourServiceRegion");

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

            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.
                        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 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?");
                                }
                            }
                        }
                    }
                }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Task to Synthesize speech into an audio file with Microsoft Speech service
        /// By Zhongzhou, Keven, 12/27/2019
        /// </summary>
        /// <param name="strPath"></param>
        /// <returns></returns>
        public static async Task <string> SynthesisToAudioFileAsync(string strPath)
        {
            string strReturn = "";

            //Insert subscription key and subscription region
            var config = SpeechConfig.FromSubscription("YourSubscriptionKey", "YourServiceRegion");

            //Set Sets property values that will be passed to service using the specified channel.
            config.SetProperty("SpeechSynthesisLanguage", "es-MX");
            config.SetProperty("SpeechSynthesisVoiceName", "es-MX-HildaRUS");
            config.SpeechSynthesisLanguage  = "es-MX";
            config.SpeechSynthesisVoiceName = "es-MX-HildaRUS";
            var fileName = @"path" + "name" + ".wav";

            //Using Speech SDK to convert text to synthesized speech in an audio file
            using (var fileOutput = AudioConfig.FromWavFileOutput(fileName))
            {
                using (var synthesizer = new SpeechSynthesizer(config, fileOutput))
                {
                    //Sends your text to the Speech service which converts it to audio.
                    StreamReader sr1     = new StreamReader(strPath);
                    var          text1   = sr1.ReadToEnd();
                    var          result1 = await synthesizer.SpeakTextAsync(text1);

                    //To make sure text was successfully synthesized when the synthesis result is returned.
                    if (result1.Reason == ResultReason.SynthesizingAudioCompleted)
                    {
                        Console.WriteLine($"Speech synthesized to [{fileName}] for text [{text1}]");
                        strReturn = fileName;
                    }
                    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?");
                        }
                    }
                }
            }

            return(strReturn);
        }
Ejemplo n.º 20
0
        public async Task <IActionResult> OnPostAsync()
        {
            var speechConfig = SpeechConfig.FromSubscription(speechKey, speechLocation);

            speechConfig.SpeechSynthesisVoiceName = LangVoice;                  //ja-Jp-KeitaNeural
            speechConfig.SpeechSynthesisLanguage  = LangVoice.Substring(0, 5);  //ja-Jp
            var audioConfig = AudioConfig.FromWavFileOutput(Path.Combine(_host.WebRootPath, "audios\\voice.wav"));

            using var synthesizer = new SpeechSynthesizer(speechConfig, audioConfig);
            var result = await synthesizer.SpeakTextAsync(TextString);

            if (result.Reason == ResultReason.SynthesizingAudioCompleted)
            {
                Result   = "Œ‹‰Ê:";
                AudioUrl = "audios/voice.wav";
            }

            return(Page());
        }
Ejemplo n.º 21
0
        public static async Task SynthesisToAudioFileAsync()
        {
            // 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("f7b1af1399664520806f4b0724765a40", "eastus");

            // Prompt for text input from the console
            Console.WriteLine("Type some text that you want to save to the audio file...");
            Console.Write("> ");

            // read the text string from the console input
            string text = Console.ReadLine();

            var fileName = "../media/text_to_speech.wav";

            using (var fileOutput = AudioConfig.FromWavFileOutput(fileName))
            {
                using (var synthesizer = new SpeechSynthesizer(config, fileOutput))
                {
                    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?");
                        }
                    }
                }
            }
        }
Ejemplo n.º 22
0
        public static async Task SynthesisToAudioFileAsync(string filename, string text)
        {
            var config = SpeechConfig.FromSubscription("24af634c423b42de910d4c84c9607f0f", Region.USWest.ToString());

            config.SpeechSynthesisVoiceName = "pt-BR-HeloisaRUS";

            if (filename == null)
            {
                filename = "helloworld.wav";
            }

            if (text == null)
            {
                text = text = "Olá! A AlphaGraphics Faria Lima 24 horas agradece a sua ligação. Entre com o ramal desejado, ou, digite: 1, para solicitar um orçamento. Para outros assuntos, por favor aguarde na linha.";
            }

            using (var fileOutput = AudioConfig.FromWavFileOutput(filename))
            {
                using (var synthesizer = new SpeechSynthesizer(config, fileOutput))
                {
                    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?");
                        }
                    }
                }
            }
        }
Ejemplo n.º 23
0
        public static async Task SynthesisToAudioFileAsync(string ssmlFile, string outputAudioFile, string subscriptionKey, string region)
        {
            Console.WriteLine($"Processing [{Path.GetFullPath(ssmlFile)}]");

            // Replace with your own subscription key and region identifier from here: https://aka.ms/speech/sdkregion
            // The default language is "en-us".
            var config = SpeechConfig.FromSubscription(subscriptionKey, region);

            var outputDirectory = Path.GetDirectoryName(outputAudioFile);

            if (!Directory.Exists(outputDirectory))
            {
                Directory.CreateDirectory(outputDirectory);
            }

            using (var fileOutput = AudioConfig.FromWavFileOutput(outputAudioFile))
            {
                using (var synthesizer = new SpeechSynthesizer(config, fileOutput))
                {
                    var ssml   = File.ReadAllText(ssmlFile);
                    var result = await synthesizer.SpeakSsmlAsync(ssml);

                    if (result.Reason == ResultReason.SynthesizingAudioCompleted)
                    {
                        Console.WriteLine($"Speech synthesized to [{Path.GetFullPath(outputAudioFile)}]");
                    }
                    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?");
                        }
                    }
                }
            }
        }
Ejemplo n.º 24
0
        public static async Task SynthesisToAudioFileAsync()
        {
            var sub         = ConfigurationManager.AppSettings["sub"];
            var region      = ConfigurationManager.AppSettings["region"] ?? "southcentralus";
            var outFilename = ConfigurationManager.AppSettings["filename"] ?? "voice.wav";
            var text        = ConfigurationManager.AppSettings["text"];
            var voice       = ConfigurationManager.AppSettings["voice"] ?? "en-US-JessaNeural";

            var config = SpeechConfig.FromSubscription(sub, region);

            using (var fileOutput = AudioConfig.FromWavFileOutput(outFilename))
            {
                using (var synthesizer = new SpeechSynthesizer(config, fileOutput))
                {
                    var xmlSpeech =
                        @"<speak version='1.0' xmlns='https://www.w3.org/2001/10/synthesis' xml:lang='en-US'>" +
                        @"<voice name='" + voice + "'>" +
                        text +
                        @"</voice></speak>";

                    var result = await synthesizer.SpeakSsmlAsync(xmlSpeech);

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

                        if (cancellation.Reason == CancellationReason.Error)
                        {
                            Console.WriteLine($"CANCELED: {cancellation.ErrorCode}\n{cancellation.ErrorDetails}");
                        }
                    }
                }
            }
        }
Ejemplo n.º 25
0
        public static async Task SpeakAsync(string txt, QuestToSpeech.Voice voice, string filePath, AzureAPIConfig config)
        {
            SpeechConfig speechConfig = SpeechConfig.FromSubscription(config.Key, config.Region);

            speechConfig.SpeechSynthesisVoiceName = voice.Name;
            speechConfig.SpeechSynthesisLanguage  = voice.LangCode;

            using (AudioConfig fileOutput = AudioConfig.FromWavFileOutput(filePath)) {
                using (SpeechSynthesizer tts = new SpeechSynthesizer(speechConfig, fileOutput)) {
                    using (SpeechSynthesisResult result = await tts.SpeakTextAsync(txt)) {
                        if (result.Reason == ResultReason.Canceled)
                        {
                            var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);

                            if (cancellation.Reason == CancellationReason.Error)
                            {
                                throw new Exception(string.Format("API Error (Code: {0}): {1}", cancellation.ErrorCode, cancellation.ErrorDetails));
                            }
                        }
                    }
                }
            }
        }
    private void downloadAudio(string text, string filePath)
    {
        SpeechConfig      speechConfig;
        SpeechSynthesizer synthesizer;

        // 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").
        speechConfig = SpeechConfig.FromSubscription("c5ab91b760b24599b3667791c08aa7d9", "uksouth");

        AudioConfig audioConfig = AudioConfig.FromWavFileOutput(filePath);

        //string temp = getQuestionText(conversationID);

        // Creates a speech synthesizer.
        // Make sure to dispose the synthesizer after use!
        using (synthesizer = new SpeechSynthesizer(speechConfig, audioConfig))
        {
            text = cleanText(text);

            // Starts speech synthesis, and returns after a single utterance is synthesized.
            string ssml = @"<speak version='1.0' xmlns='https://www.w3.org/2001/10/synthesis' xml:lang='en-US'><voice name='" + masterScript.voice + "'>" + text + "</voice></speak>";

            using (var result = synthesizer.SpeakSsmlAsync(ssml).Result)
            {
                // Checks result.
                if (result.Reason == ResultReason.SynthesizingAudioCompleted)
                {
                    Debug.Log("Downloaded Audio");
                }
                else if (result.Reason == ResultReason.Canceled)
                {
                    var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                    Debug.Log(cancellation.Reason);
                }
            }
        }
    }
        private async void SpeechSynthesisToFile_ButtonClicked()
        {
            if (!AreKeysValid())
            {
                NotifyUser("Subscription Key is missing!", NotifyType.ErrorMessage);
                return;
            }
            else
            {
                NotifyUser(" ", NotifyType.StatusMessage);
            }

            // User can also specify another under the ApplicationData.LocalFolder or Package.InstalledLocation
            var filePath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "outputaudio.wav");

            // Creates an instance of a speech config with specified and service region (e.g., "westus").
            var config = SpeechConfig.FromSubscription(this.SubscriptionKey, this.Region);

            config.SpeechSynthesisLanguage = this.SynthesisLanguage;

            // Creates a speech synthesizer using file as audio output.
            using (var audioOutput = AudioConfig.FromWavFileOutput(filePath))
                using (var synthesizer = new SpeechSynthesizer(config, audioOutput))
                {
                    // Subscribes to events.
                    synthesizer.SynthesisStarted += (s, e) =>
                    {
                        NotifyUser($"Speech synthesis started.", NotifyType.StatusMessage);
                    };

                    synthesizer.Synthesizing += (s, e) =>
                    {
                        NotifyUser($"{e.Result.AudioData.Length} bytes received.", NotifyType.StatusMessage);
                    };

                    synthesizer.SynthesisCompleted += (s, e) =>
                    {
                        NotifyUser($"Speech synthesis completed.", NotifyType.StatusMessage);
                    };

                    synthesizer.SynthesisCanceled += (s, e) =>
                    {
                        var cancellation = SpeechSynthesisCancellationDetails.FromResult(e.Result);

                        StringBuilder sb = new StringBuilder();
                        sb.AppendLine($"CANCELED: Reason={cancellation.Reason}");
                        sb.AppendLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                        sb.AppendLine($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");

                        NotifyUser(sb.ToString(), NotifyType.ErrorMessage);
                    };

                    // Waits for completion.
                    using (var result = await synthesizer.SpeakTextAsync(this.TextForSynthesizingTextBox.Text).ConfigureAwait(false))
                    {
                        if (result.Reason == ResultReason.SynthesizingAudioCompleted)
                        {
                            NotifyUser($"Speech synthesis completed. The audio has been saved to {filePath}.", NotifyType.StatusMessage);
                        }
                    }
                }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Return an audio file for the passed in text
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public async Task <byte[]> TextToSpeechFile(string text)
        {
            if (!_availableServices.Contains(AzureServiceType.Speech))
            {
                return(null);
            }

            _speechSemaphore.Wait();
            try
            {
                StorageFolder localFolder = ApplicationData.Current.LocalFolder;

                //TODO Update to use PullAudioInputStream
                StorageFile storageFile = await localFolder.CreateFileAsync("TTSAudio.wav", CreationCollisionOption.ReplaceExisting);

                if (!string.IsNullOrWhiteSpace(CurrentSpeakingVoice))
                {
                    _speechConfig.SpeechSynthesisVoiceName = CurrentSpeakingVoice;
                }

                SetProfanityOption(AzureProfanitySetting);

                using (var fileOutput = AudioConfig.FromWavFileOutput(storageFile.Path))
                {
                    using (var synthesizer = new SpeechSynthesizer(_speechConfig, fileOutput))
                    {
                        var result = await synthesizer.SpeakTextAsync(text);

                        if (result.Reason == ResultReason.Canceled)
                        {
                            var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                            _logger.LogWarning($"Call cancelled.  {cancellation.Reason}");

                            if (cancellation.Reason == CancellationReason.Error)
                            {
                                _logger.Log($"Cancel error code = {cancellation.ErrorCode}");
                                _logger.Log($"Cancel details = {cancellation.ErrorDetails}");

                                if (cancellation.ErrorCode == CancellationErrorCode.NoError)
                                {
                                    _logger.Log("You may be having an authorization issue, are your keys correct and up to date?");
                                }
                            }
                            return(null);
                        }

                        _logger.Log($"Audio Received. '{result.Reason}'");
                        return(result.AudioData);
                    }
                }
            }
            catch (Exception ex)
            {
                string message = "Failed processing text to speech.";
                _logger.Log(message, ex);
                return(null);
            }
            finally
            {
                _speechSemaphore.Release();
            }
        }
Ejemplo n.º 29
0
        private bool SynthesizeAudio(string outputFile, bool isSsml, string text)
        {
            if (this.synthesizerType == "Windows")
            {
                using var synth = new System.Speech.Synthesis.SpeechSynthesizer();

                try {
                    synth.InjectOneCoreVoices();
                }
                catch {
                }

                synth.Rate   = rate;
                synth.Volume = volume;

                synth.SetOutputToWaveFile(outputFile);

                finished = false;
                failed   = false;

                synth.SpeakCompleted += OnSpeakCompleted;

                if (isSsml)
                {
                    synth.SpeakSsmlAsync(text);
                }
                else
                {
                    synth.SpeakAsync(text);
                }

                while (!finished)
                {
                    Thread.Sleep(100);
                }

                return(true);
            }
            else
            {
                RenewToken();

                using var audioConfig = AudioConfig.FromWavFileOutput(outputFile);
                using var synthesizer = new Microsoft.CognitiveServices.Speech.SpeechSynthesizer(config, audioConfig);

                finished = false;
                failed   = false;

                synthesizer.SynthesisCanceled  += OnSynthesisCanceled;
                synthesizer.SynthesisCompleted += OnSynthesisCompleted;

                if (isSsml)
                {
                    synthesizer.SpeakSsmlAsync(text);
                }
                else
                {
                    synthesizer.SpeakTextAsync(text);
                }

                while (!finished)
                {
                    Thread.Sleep(100);
                }

                return(!failed);
            }
        }