SpeechSynthesizer 类使用指南
1. 添加引用和命名空间

  • 引用程序集:System.Speech.dll
  • 引入命名空间:
using System.Speech.Synthesis;

2. 初始化 SpeechSynthesizer

// 创建 SpeechSynthesizer 实例
SpeechSynthesizer synth = new SpeechSynthesizer();

3. 基本功能:文本转语音
3.1 同步播放语音

synth.Speak("Hello, welcome to the world of speech synthesis.");

3.2 异步播放语音

synth.SpeakAsync("This text will be spoken asynchronously.");
// 可随时取消异步操作
synth.SpeakAsyncCancelAll();

4. 配置语音参数
4.1 设置语速(-10 到 10)

synth.Rate = 2; // 加快语速

4.2 设置音量(0 到 100)

synth.Volume = 75; // 75% 音量

4.3 选择语音库

// 获取所有已安装的语音
foreach (InstalledVoice voice in synth.GetInstalledVoices())
{
    Console.WriteLine(voice.VoiceInfo.Name);
}

// 设置特定语音(需确保已安装)
synth.SelectVoice("Microsoft Zira Desktop"); // 英文女声
synth.SelectVoice("Microsoft Huihui Desktop"); // 中文女声

5. 输出到文件

// 设置输出为 WAV 文件
synth.SetOutputToWaveFile(@"C:\output\speech.wav");
synth.Speak("This audio will be saved to a file.");
synth.SetOutputToDefaultAudioDevice(); // 恢复默认输出

6. 事件处理

// 订阅语音合成完成事件
synth.SpeakCompleted += (sender, e) => 
{
    Console.WriteLine("Speech synthesis completed!");
};

synth.SpeakAsync("Processing complete.");

7. 完整示例代码

using System;
using System.Speech.Synthesis;

class Program
{
    static void Main()
    {
        using (SpeechSynthesizer synth = new SpeechSynthesizer())
        {
            // 配置参数
            synth.Volume = 80;
            synth.Rate = 1;
            synth.SelectVoice("Microsoft Huihui Desktop");

            // 注册事件
            synth.SpeakCompleted += Synth_SpeakCompleted;

            // 同步播放
            synth.Speak("开始播放。");

            // 异步播放
            synth.SpeakAsync("这是一段异步播放的语音。");

            Console.WriteLine("按任意键退出...");
            Console.ReadKey();
        }
    }

    private static void Synth_SpeakCompleted(object sender, SpeakCompletedEventArgs e)
    {
        Console.WriteLine("语音播放完成。");
    }
}

注意事项
语音包依赖:

  • 需在操作系统中安装对应的语音库(如中文语音包)。
  • 在 Windows 中可通过“控制面板” → “语音识别” → “文本到语音”安装。

异常处理:

try
{
    synth.Speak("Test");
}
catch (Exception ex)
{
    Console.WriteLine($"错误: {ex.Message}");
}

资源释放:

  • 使用 using 语句或在结束时调用 Dispose() 释放资源。

常见问题解决

  • 无声音输出:检查系统音量、默认音频设备设置。
  • 语音不生效:确认 SelectVoice 的名称与已安装的语音库匹配。
  • 权限问题:以管理员权限运行程序(如需写入系统目录)。

通过上述步骤,您可快速掌握 SpeechSynthesizer 类的核心功能,实现文本到语音的转换。

Logo

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

更多推荐