中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
文本转语音的方法
微信扫码分享
import { BusinessError } from '@kit.BasicServicesKit'; // 设置创建引擎参数 let extraParam: Record<string, Object> = {"style": 'interaction-broadcast', "locate": 'CN', "name": 'EngineName'}; let initParamsInfo: textToSpeech.CreateEngineParams = { language: 'zh-CN', person: 0, online: 1, extraParams: extraParam }; try { // 调用createEngine方法 textToSpeech.createEngine(initParamsInfo, (err: BusinessError, textToSpeechEngine: textToSpeech.TextToSpeechEngine) => { if (!err) { console.info('createEngine is success'); // 接收创建引擎的实例 ttsEngine = textToSpeechEngine; } else { // 创建引擎失败时返回错误码1003400005,可能原因:引擎不存在、资源不存在、创建引擎超时 console.error("errCode is " + JSON.stringify(err.code)); console.error("errMessage is " + JSON.stringify(err.message)); } }); } catch (error) { let message = (error as BusinessError).message; let code = (error as BusinessError).code; console.error(`createEngine failed, error code: ${code}, message: ${message}.`) } // 设置回调对象 let speakListener: textToSpeech.SpeakListener = { // 开始播报回调 onStart(requestId: string, response: textToSpeech.StartResponse) { console.info('onStart: ' + 'requestId: ' + requestId + ' response: ' + JSON.stringify(response)); }, // 合成完成及播报完成回调 onComplete(requestId: string, response: textToSpeech.CompleteResponse) { console.info('onComplete: ' + 'requestId: ' + requestId + ' response: ' + JSON.stringify(response)); }, // 停止播报回调 onStop(requestId: string, response: textToSpeech.StopResponse) { console.info('onStop: ' + 'requestId: ' + requestId + ' response: ' + JSON.stringify(response)); }, // 返回音频流 onData(requestId: string, audio: ArrayBuffer, response: textToSpeech.SynthesisResponse) { console.log('speakListener onData: ' + ' requestId: ' + requestId+ ' sequence: ' + JSON.stringify(response) + ' audio: ' + audio); }, // 错误回调 onError(requestId: string, errorCode: number, errorMessage: string) { console.error('OnError: ' + 'requestId: ' + requestId + ' errorCode: ' + errorCode + 'errorMessage: ' + errorMessage); } }; // 调用回调方法 ttsEngine.setListener(speakListener); // 设置播报相关参数 let extraParam: Record<string, Object> = {"queueMode": 0, "speed": 1, "volume": 2, "pitch": 1, "languageContext": 'zh-CN', "audioType": "pcm", "soundChannel": 3, "playType":1} let speakParams: textToSpeech.SpeakParams = { requestId: '123456', extraParams: extraParam }; // 调用播报方法 this.ttsEngine.speak(this.originalText, speakParams);