🎯 目标

实现一个语音输入组件 VoiceInput,适用于:

  • 实时语音转文字(如问答、搜索、命令输入)
  • 提供“开始录音”按钮,支持语音识别状态提示
  • 接入 HarmonyOS 语音识别引擎(SpeechRecognizer)或模拟 API
  • 识别后回调文字内容,可用于搜索栏、表单、聊天输入框
  • 后续支持语音指令映射功能(如“打开设置”)

🧱 交互示意

🎙️ [点击开始语音输入]
识别中... 语音转文字中...
✅ 已识别:请打开课程页面

🧰 组件实现:VoiceInput.ets(模拟识别)

⚠️ 提示:以下使用模拟识别逻辑。实际部署请接入语音识别服务,例如 SpeechRecognizer

@Component
export struct VoiceInput {
  @Prop onResult: (text: string) => void = () => {}
  @State recognizing: boolean = false
  @State result: string = ''

  build() {
    Column({ space: 12 }).alignItems(HorizontalAlign.Center).padding(20) {
      Button(this.recognizing ? '识别中...' : '🎙️ 开始语音输入')
        .type(ButtonType.Normal)
        .onClick(() => this.startRecognition())

      if (this.result) {
        Text(`✅ 识别结果:${this.result}`)
          .fontSize(14)
          .fontColor('#333')
      }
    }
  }

  private async startRecognition() {
    if (this.recognizing) return
    this.recognizing = true
    this.result = ''

    // 模拟录音识别耗时
    await new Promise(res => setTimeout(res, 2000))

    const simulatedText = '请打开课程页面'
    this.result = simulatedText
    this.recognizing = false
    this.onResult(simulatedText)
  }
}

📦 使用示例

@Entry
@Component
struct DemoVoiceInput {
  @State command: string = ''

  build() {
    Column({ space: 20 }) {
      VoiceInput({
        onResult: text => this.command = text
      })

      if (this.command) {
        Text(`你说的是:${this.command}`).fontSize(15).fontColor('#007DFF')
      }
    }.padding(20)
  }
}

✨ 可扩展能力建议

功能说明
接入语音识别服务使用 HarmonyOS SpeechRecognizer 或 HMS ML Kit 接口
支持长语音识别 / 连续输入实现实时流式识别转文字
关键词匹配 / 命令触发如识别“打开设置”→ 跳转设置页面
支持方言/多语种识别可设置识别语言:中文、英文、粤语等
录音动画反馈 + 麦克风权限提示UI 提示用户正在说话 / 请求系统麦克风权限

📘 下一篇预告

第47篇:【HarmonyOS 5.0.0 或以上】构建文件管理器组件 FileManager:支持目录树 / 文件操作 / 多选移动删除

更多推荐