一、前言:为什么现在必须重视语音能力?
在鸿蒙生态逐步完善的当下,跨设备交互已成为核心能力。语音作为"天然输入方式",在车机、可穿戴、智能家居等场景下具有不可替代的优势。
相比传统触控输入,语音具备:
本文基于 HarmonyOS6,结合实际项目经验,从语音识别(ASR)实战角度出发,完整演示一个"语音记事本"应用的实现。
二、实战场景设计:语音记事本
目标功能:
- • 适配 HarmonyOS 6 Stage 模型
三、权限配置
module.json5 中声明麦克风权限:
{ "requestPermissions": [ { "name": "ohos.permission.MICROPHONE" } ]}
四、核心代码实现(可运行示例)
Index.ets
import speech from '@ohos.speech';import prompt from '@ohos.promptAction';@Entry@Componentstruct Index { @State resultText: string = "点击开始识别"; private recognizer: speech.SpeechRecognizer | undefined; aboutToAppear() { this.recognizer = speech.createSpeechRecognizer(); } aboutToDisappear() { this.recognizer?.destroy(); } startRecognize() { if (!this.recognizer) { prompt.showToast({ message: "识别器未初始化" }); return; } let option: speech.RecognizeOption = { language: 'zh-CN', resultMode: speech.ResultMode.FINAL_RESULT, engineType: speech.EngineType.LOCAL }; this.recognizer.startRecognize(option, { onResult: (result: speech.SpeechRecognitionResult) => { this.resultText = result.result; }, onError: (error) => { this.resultText = "识别失败:" + JSON.stringify(error); } }); } stopRecognize() { this.recognizer?.stopRecognize(); } build() { Column({ space: 20 }) { Text(this.resultText) .fontSize(20) .width('90%') Button("开始识别") .onClick(() => { this.startRecognize(); }) Button("停止识别") .onClick(() => { this.stopRecognize(); }) } .width('100%') .height('100%') .justifyContent(FlexAlign.Center) }}
五、关键技术解析
1. 生命周期管理
SpeechRecognizer 占用系统资源,必须在页面销毁时释放:
aboutToDisappear() { this.recognizer?.destroy();}
否则会导致二次初始化失败。
2. 本地与云端识别对比
生产建议:优先本地,异常时降级云端。
3. 实时识别模式
将 resultMode 改为:
resultMode: speech.ResultMode.PARTIAL_RESULT
即可实现实时字幕效果。
六、架构优化建议
建议封装服务层:
class VoiceService { private recognizer = speech.createSpeechRecognizer(); start(option, callback) { this.recognizer.startRecognize(option, callback); } stop() { this.recognizer.stopRecognize(); } destroy() { this.recognizer.destroy(); }}
页面仅负责 UI。
七、实战踩坑总结
八、总结
本篇文章完成了:
如果你正在构建车机、IoT 或跨设备应用,语音能力是未来重要入口。