C# 实现 Cortana 语音朗读输入文本

准备工作

  1. 安装语音包
    • 在 Windows 10 设置中,确保已安装所需的语音包。
    • 路径:设置 -> 时间和语言 -> 语音 -> 管理语音

win10在设置找到安装的语音包,确然电脑上安装了语音包

  1. 创建 C# 控制台程序

    • 打开 Visual Studio,创建一个新的 C# 控制台项目。
  2. 添加 Speech 引用

    • 右键点击项目 -> 添加 -> 引用
    • 程序集 -> 框架 中找到并添加 System.Speech

添加Speecj

  1. 添加命名空间
    using System.Speech.Synthesis; // 用于语音合成
    

代码实现

将以下代码复制到 Main 函数中:

using System;
using System.Speech.Synthesis;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("请输入要朗读的文本:");
        var inputText = Console.ReadLine(); // 读取用户输入

        SpeechSynthesizer speech = new SpeechSynthesizer(); // 创建语音合成器对象
        speech.Rate = 1; // 设置语速(-10 到 10,默认 0)
        speech.Volume = 100; // 设置音量(0 到 100)
        speech.SelectVoice("Microsoft Huihui Desktop"); // 设置中文语音
        speech.Speak(inputText); // 朗读输入的文本
    }
}

声音的查看


代码解释

  1. SpeechSynthesizer speech = new SpeechSynthesizer();

    • 创建一个语音合成器对象,用于生成语音。
  2. speech.Rate = 1;

    • 设置语速,范围为 -10(最慢)到 10(最快),默认值为 0
  3. speech.Volume = 100;

    • 设置音量,范围为 0(静音)到 100(最大音量)。
  4. speech.SelectVoice("Microsoft Huihui Desktop");

    • 选择语音包中的特定语音(如中文语音“Microsoft Huihui Desktop”)。
  5. speech.Speak(inputText);

    • 朗读用户输入的文本。

查看已安装的语音

可以通过以下代码查看系统中已安装的语音包:

using System;
using System.Speech.Synthesis;

class Program
{
    static void Main(string[] args)
    {
        SpeechSynthesizer speech = new SpeechSynthesizer();
        foreach (var voice in speech.GetInstalledVoices())
        {
            Console.WriteLine(voice.VoiceInfo.Name); // 输出已安装的语音名称
        }
    }
}
  • 输出
    Microsoft Huihui Desktop
    Microsoft Zira Desktop
    

安装的语音

  • 切换语音:
    speech.SelectVoice("Microsoft Huihui Desktop"); 中的语音名称替换为其他已安装的语音名称。
Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐