中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
文本转语音的方法
微信扫码分享
import { BusinessError } from '@kit.BasicServicesKit'; let asrEngine: speechRecognizer.SpeechRecognitionEngine; let requestId: string = '123456'; // 创建引擎,通过callback形式返回 // 设置创建引擎参数 let extraParam: Record<string, Object> = {"locate": "CN", "recognizerMode": "short"}; let initParamsInfo: speechRecognizer.CreateEngineParams = { language: 'zh-CN', online: 1, extraParams: extraParam } // 调用createEngine方法 speechRecognizer.createEngine(initParamsInfo, (err: BusinessError, speechRecognitionEngine: speechRecognizer.SpeechRecognitionEngine) => { if (!err) { console.info('createEngine is success'); //接收创建引擎的实例 asrEngine = speechRecognitionEngine; } else { //无法创建引擎时返回错误码1002200008,原因:引擎正在销毁中 console.error("errCode: " + err.code + " errMessage: " + JSON.stringify(err.message)); } }); // 创建回调对象 let setListener: speechRecognizer.RecognitionListener = { // 开始识别成功回调 onStart(sessionId: string, eventMessage: string) { console.info("onStart sessionId: " + sessionId + "eventMessage: " + eventMessage); }, // 事件回调 onEvent(sessionId: string, eventCode: number, eventMessage: string) { console.info("onEvent sessionId: " + sessionId + "eventCode: " + eventCode + "eventMessage: " + eventMessage); }, // 识别结果回调,包括中间结果和最终结果 onResult(sessionId: string, result: speechRecognizer.SpeechRecognitionResult) { console.info("onResult sessionId: " + sessionId + "sessionId: " + JSON.stringify(result)); }, // 识别完成回调 onComplete(sessionId: string, eventMessage: string) { console.info("onComplete sessionId: " + sessionId + "eventMessage: " + eventMessage); }, // 错误回调,错误码通过本方法返回 // 返回错误码1002200002,开始识别失败,重复启动startListening方法时触发 // 更多错误码请参考错误码参考 onError(sessionId: string, errorCode: number, errorMessage: string) { console.error("onError sessionId: " + sessionId + "errorCode: " + errorCode + "errorMessage: " + errorMessage); } } // 设置回调 asrEngine.setListener(setListener); let audioParam: speechRecognizer.AudioInfo = {audioType: 'pcm', sampleRate: 16000, soundChannel: 1, sampleBit: 16}; let extraParam: Record<string, Object> = {"vadBegin": 2000, "vadEnd": 3000, "maxAudioDuration": 40000}; let recognizerParams: speechRecognizer.StartParams = { sessionId: requestId, audioInfo: audioParam, extraParams: extraParam } // 调用开始识别方法 asrEngine.startListening(recognizerParams); let unit8Array: Uint8Array = new Uint8Array(); // 可以通过如下方式获取音频流:1、通过录音获取音频流;2、从音频文件中读取音频流 //2、从音频文件中读取音频流:demo参考 // 写入音频流,音频流长度仅支持640字节或1280字节asrEngine.writeAudio(requestId, unit8Array);