C# 实现 Cortana 语音朗读输入文本
我写你读输入一段string然后系统会把输入的string读出来准备工作添加语音开始工作创建c#控制台程序。在引用中添加添加Speed的引用,声音主要是这个输入。添加命名空间using System.Speech.Synthesis;//生意播放...
·
C# 实现 Cortana 语音朗读输入文本
准备工作
- 安装语音包:
- 在 Windows 10 设置中,确保已安装所需的语音包。
- 路径:
设置 -> 时间和语言 -> 语音 -> 管理语音
。
-
创建 C# 控制台程序:
- 打开 Visual Studio,创建一个新的 C# 控制台项目。
-
添加 Speech 引用:
- 右键点击项目 ->
添加 -> 引用
。 - 在
程序集 -> 框架
中找到并添加System.Speech
。
- 右键点击项目 ->
- 添加命名空间:
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); // 朗读输入的文本
}
}
代码解释
-
SpeechSynthesizer speech = new SpeechSynthesizer();
:- 创建一个语音合成器对象,用于生成语音。
-
speech.Rate = 1;
:- 设置语速,范围为
-10
(最慢)到10
(最快),默认值为0
。
- 设置语速,范围为
-
speech.Volume = 100;
:- 设置音量,范围为
0
(静音)到100
(最大音量)。
- 设置音量,范围为
-
speech.SelectVoice("Microsoft Huihui Desktop");
:- 选择语音包中的特定语音(如中文语音“Microsoft Huihui Desktop”)。
-
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");
中的语音名称替换为其他已安装的语音名称。
更多推荐
所有评论(0)