Blazor Server中使用SpeechSynthesizer保存音频且不播放的问题
Blazor Server中使用微软文本转语音服务保存音频文件并避免播放声音
你当前的代码调用SpeakSsmlAsync时,默认会通过系统音频设备播放合成语音。要实现只保存音频文件、不向用户播放声音的需求,只需在创建SpeechSynthesizer实例时禁用音频输出即可。
核心修改点
创建SpeechSynthesizer时,第二个参数传入null(表示不关联任何音频输出设备),替代默认的自动播放配置:
using (var speechSynthesizer = new SpeechSynthesizer(speechConfig, null))
这里的第二个参数是AudioConfig类型,传null会告诉SDK仅生成音频数据,不执行播放操作。
修改后的完整代码
using Microsoft.CognitiveServices.Speech; public class TextToSpeechService : ITextToSpeechService { public async Task SpeakSsmlAndSaveToFile(string text, string filePath) { var speechConfig = SpeechConfig.FromSubscription("5c4d780b81cb40fca6bd555cc3148765", "westeurope"); speechConfig.SpeechSynthesisVoiceName = "sk-SK-LukasNeural"; string ssml = $"<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='en-US'>" + $"<voice name='sk-SK-LukasNeural'>{text}</voice></speak>"; // 修正路径转义,用正斜杠或双反斜杠避免语法错误 filePath = "wwwroot/Audio/DictationRecordings/" + filePath; // 传入null禁用音频播放,仅生成音频数据 using (var speechSynthesizer = new SpeechSynthesizer(speechConfig, null)) { var result = await speechSynthesizer.SpeakSsmlAsync(ssml); if (result.Reason == ResultReason.SynthesizingAudioCompleted) { Console.WriteLine($"Speech synthesized for SSML: [{ssml}], and the result is being written to file: {filePath}"); using (var audioDataStream = AudioDataStream.FromResult(result)) { await audioDataStream.SaveToWaveFileAsync(filePath); } } else if (result.Reason == ResultReason.Canceled) { var cancellation = SpeechSynthesisCancellationDetails.FromResult(result); Console.WriteLine($"CANCELED: Reason={cancellation.Reason}"); if (cancellation.Reason == CancellationReason.Error) { Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}"); Console.WriteLine($"CANCELED: ErrorDetails= [{cancellation.ErrorDetails}]"); Console.WriteLine($"CANCELED: Did you set the speech resource key and region values?"); } } } } }
额外提示
- 不要硬编码订阅密钥和区域,建议从Blazor的
appsettings.json配置文件中读取,避免密钥泄露。 - 确保
wwwroot/Audio/DictationRecordings目录存在,否则保存文件会抛出异常,可在代码中添加目录检查与创建逻辑。
内容的提问来源于stack exchange,提问作者Tomáš Staroň
相关产品推荐
相关产品推荐

