C# 非常简单的文字转语音实现

之前废了老大劲实现了文本转语音功能,结果发现C#官方有个非常简单的实现,泪流满面,应该是用不上了,记录一下方便后来人吧

感谢 https://zhuanlan.zhihu.com/p/32960822565

需要先在nuget中引用System.Speech包,然后就是下面的使用方式

        public void Test() {
            string text = "测试123abc_@xyz";
            //Speak(text);
            GenerateAudioFile(text, "D:\\text.wav");
        }
        /// <summary>
        /// 播放语音
        /// </summary> 
        static void Speak(string text) {
            using (SpeechSynthesizer synthesizer = new SpeechSynthesizer()) {
                synthesizer.Speak(text);
            }
        }
        /// <summary>
        /// 生成语音文件
        /// </summary> 
        static void GenerateAudioFile(string text, string path) {
            using (SpeechSynthesizer synthesizer = new SpeechSynthesizer()) {
                using (MemoryStream stream = new MemoryStream()) {
                    synthesizer.SetOutputToWaveStream(stream); // 设置语音合成的输出目标为内存流 
                    synthesizer.Speak(text);
                    using (FileStream fileStream = new FileStream(path, FileMode.Create)) {
                        stream.Seek(0, SeekOrigin.Begin);
                        stream.CopyTo(fileStream);
                    }
                }
            }
        }

 

posted @ 2025-03-27 17:25  WmW  阅读(164)  评论(0)    收藏  举报