Microsoft Cognitive Services Speech SDK点击停止按钮无法终止语音问题
解决方案
要实现终止语音播放的功能,核心是让stopTextSpeech方法能访问到语音合成器实例,并调用SDK提供的停止方法。修改步骤如下:
1. 保存语音合成器实例
将SpeechSynthesizer实例改为服务的私有成员变量,确保stopTextSpeech能访问到它。
2. 实现停止逻辑
在stopTextSpeech方法中调用SDK的stopSpeakingAsync方法终止播放,同时清理资源避免内存泄漏。
修改后的完整代码
import { Injectable } from '@angular/core'; import { ApplicationSettings } from 'app/modules/types/appConfiguration'; import { AppConfigService } from 'app/services/app.config.service'; import * as sdk from 'microsoft-cognitiveservices-speech-sdk'; @Injectable({ providedIn: 'root', }) export class SpeechService { private appSettings: ApplicationSettings; // 保存语音合成器实例 private synthesizer: sdk.SpeechSynthesizer | null = null; constructor(appConfigService: AppConfigService) { this.appSettings = appConfigService.getAppSettings(); } textToSpeech(languageKey, voiceKey, text: string) { // 如果已有正在运行的合成器,先停止并释放 if (this.synthesizer) { this.stopTextSpeech(); } const speechConfig = sdk.SpeechConfig.fromSubscription( this.appSettings.speechServices.key, this.appSettings.speechServices.region ); speechConfig.speechSynthesisLanguage = languageKey; speechConfig.speechSynthesisVoiceName = voiceKey; this.synthesizer = new sdk.SpeechSynthesizer( speechConfig, sdk.AudioConfig.fromDefaultSpeakerOutput() ); // 播放结束后自动清理资源 this.synthesizer.speakTextAsync(text, () => { this.synthesizer?.close(); this.synthesizer = null; }, (error) => { console.error('语音合成失败:', error); this.synthesizer?.close(); this.synthesizer = null; } ); } stopTextSpeech(): void { if (this.synthesizer) { // 调用SDK的停止方法 this.synthesizer.stopSpeakingAsync( () => { this.synthesizer?.close(); this.synthesizer = null; }, (error) => { console.error('停止语音播放失败:', error); this.synthesizer?.close(); this.synthesizer = null; } ); } } }
关键说明
- 保存合成器实例:将
synthesizer设为服务的私有属性,解决原代码中实例局部化无法访问的问题。 - 重复播放处理:启动新的语音合成前,先检查并停止已有合成器,避免多个音频同时播放。
- 资源清理:无论是播放完成还是主动停止,都调用
close()方法释放合成器资源,防止内存泄漏。
内容的提问来源于stack exchange,提问作者Manoj Prasanna
相关产品推荐
相关产品推荐

