C#和微软System.Speech.Synthesis库实现语音合成
C#和微软System.Speech.Synthesis库实现语音合成
一、基础语音合成示例
using System;
using System.Speech.Synthesis;class Program
{static void Main(){using (SpeechSynthesizer synth = new SpeechSynthesizer()){// 1. 选择语音(需系统已安装对应语音包)synth.SelectVoice("Microsoft Zira Desktop"); // 中文语音// synth.SelectVoice("Microsoft David Desktop"); // 英文语音// 2. 设置语音属性synth.Rate = 0; // 语速(-10到10,默认5)synth.Volume = 90; // 音量(0-100)// 3. 同步朗读文本synth.Speak("您好,欢迎使用微软语音合成技术!");// 4. 异步朗读(不阻塞主线程)synth.SpeakAsync("正在异步播放语音...");Console.WriteLine("异步朗读已启动...");}}
}
二、高级功能实现
2.1 使用SSML控制语音效果
public string GenerateSsml(string text)
{return $@"<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='zh-CN'><voice name='Microsoft Zira Desktop'><prosody pitch='+10%' rate='fast'><emphasis level='strong'>重要通知:</emphasis>{text}</prosody></voice></speak>";
}// 使用示例
synth.SpeakSsml(GenerateSsml("系统检测到异常操作!"));
2.2 语音文件保存
public void SaveToWav(string text, string filePath)
{using (SpeechSynthesizer synth = new SpeechSynthesizer()){// 设置音频格式SpeechAudioFormatInfo format = new SpeechAudioFormatInfo(22050, // 采样率AudioBitsPerSample.Sixteen, // 16位AudioChannel.Mono); // 单声道// 保存到文件synth.SetOutputToWaveFile(filePath, format);synth.Speak(text);synth.SetOutputToNull(); // 释放资源}
}// 使用示例
SaveToWav("请检查设备连接状态!", "output.wav");
三、完整功能类封装
public class VoiceAssistant
{private readonly SpeechSynthesizer _synth;public VoiceAssistant(){_synth = new SpeechSynthesizer();InitializeVoices();}private void InitializeVoices(){// 获取系统所有语音var voices = _synth.GetInstalledVoices();foreach (var voice in voices){Console.WriteLine($"可用语音: {voice.VoiceInfo.Name} [{voice.VoiceInfo.Language}]");}}public void Configure(VoiceGender gender = VoiceGender.Neutral, VoiceAge age = VoiceAge.Adult,int rate = 0,int volume = 100){_synth.SelectVoiceByHints(gender, age);_synth.Rate = rate;_synth.Volume = volume;}public void Speak(string text){try{_synth.Speak(text);}catch (Exception ex){Console.WriteLine($"语音合成失败: {ex.Message}");}}public void Shutdown(){_synth.Dispose();}
}// 使用示例
var assistant = new VoiceAssistant();
assistant.Configure(VoiceGender.Female, VoiceAge.Adult, rate: -2);
assistant.Speak("正在为您查询天气情况...");
四、异常处理与资源管理
public class SafeTtsService : IDisposable
{private SpeechSynthesizer _synth;private bool _disposed = false;public SafeTtsService(){try{_synth = new SpeechSynthesizer();}catch (PlatformNotSupportedException){throw new InvalidOperationException("当前系统不支持语音合成功能");}}public void Dispose(){Dispose(true);GC.SuppressFinalize(this);}protected virtual void Dispose(bool disposing){if (!_disposed){if (disposing){_synth?.Dispose();}_disposed = true;}}
}
五、关键配置说明
-
语音引擎安装
- Windows 10/11 默认包含中文语音包(如Microsoft Huihui、Microsoft Zira)
- 如需更多语音,可通过微软商店安装"Microsoft Speech Language Pack"
-
SSML支持
- 支持语调控制(
<prosody>
)、强调(<emphasis>
)、静默(<break>
) - 示例:
<break time='500ms'/>
添加0.5秒停顿
- 支持语调控制(
-
性能优化
// 启用异步处理避免界面卡顿 private async Task AsyncSpeak(string text) {await Task.Run(() => _synth.Speak(text)); }
参考项目 C# 语音合成例子源码(TTS微软库) www.youwenfan.com/contentcsh/57531.html
六、完整项目结构
- VoiceApp.sln├─ VoiceCore/ # 核心逻辑│ ├─ TtsService.cs # 语音服务类│ └─ VoiceConfig.cs # 配置管理├─ Models/ # 数据模型│ └─ VoiceSettings.cs # 语音参数配置└─ Views/ # 用户界面└─ MainForm.xaml # 控制面板
七、部署注意事项
-
目标系统要求
- Windows 10 1809 或更高版本
- .NET Framework 4.7.2+
- 安装语音合成引擎(通过控制面板 > 语音识别 > 安装语音包)
-
安装包配置
<!-- app.manifest --> <requestedExecutionLevel level="asInvoker" uiAccess="false" /> <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"><application><!-- 支持高DPI显示 --><supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/></application> </compatibility>