HarmonyOS Next 语音交互组件开发实践(一)

111 阅读1分钟

HarmonyOS Next 语音交互组件开发实践

概述

在 HarmonyOS Next 应用开发中,实现语音交互功能可以提升用户体验。下面将介绍如何构建一个语音交互组件,实现语音录制、转文字以及取消等操作。

核心代码功能及对应代码段

1. 组件状态初始化
@Component
export struct VoiceComponent {
  @State bottomHeight: number = 0; 
  @Consume('yMax') yMax: number; 
  @Consume('yMin') yMin: number; 
  @State isListening: boolean = false;
  @State count: number = Const.OPACITY_FALSE;
  @Consume('flagUpOpacity') flagUpOpacity: number; 
  @State flagInfoOpacity: number = Const.OPACITY_FALSE; 
  @State maxNumber: number = Const.OPACITY_FALSE; 
  @State minNumber: number = Const.OPACITY_FALSE; 
  @State timeStart: number = Const.OPACITY_FALSE; 
  @State timeEnd: number = Const.OPACITY_FALSE; 
  @State timeAv: number = Const.OPACITY_FALSE; 
  @Consume('waterRipplesBg') waterRipplesBg: Resource;
  @Consume('backgroundCancel') backgroundCancel: Color;
  @Consume('fontColorCancel') fontColorCancel: Color;
  @Consume('backgroundWord') backgroundWord: Color;
  @Consume('fontColorWord') fontColorWord: Color;
  @Consume('backgroundVoice') backgroundVoice: Color;
  @Consume('fontColorVoice') fontColorVoice: Color;
  @Consume('mode') mode: number;
  avoidAreaType: number = window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR;
  avRecord = new AudioRecorder();
  onSend = (text: string, type: number): void => {};
}
  • 利用 @State@Consume 装饰器初始化组件的各种状态,如是否正在监听、音频振幅、时间戳等。
  • 创建 AudioRecorder 实例用于音频录制。
2. 语音录制开始与结束
LongPressGesture()
  .onAction(() => {
    this.mode = Const.VOICE;
    this.timeStart = Math.floor(new Date().getTime() / Const.ANIMATION_DURATION);
    this.flagInfoOpacity = Const.OPACITY_FALSE;
    this.isListening = !this.isListening;
    this.flagUpOpacity = Const.OPACITY_TRUE;
    this.avRecord.startRecordingProcess();
    this.count = setInterval(() => {
      if (this.avRecord.maxAmplitude > Const.MIN_AMPLITUDE) {
        this.maxNumber = (this.avRecord.maxAmplitude) / Const.MAX_AMPLITUDE * Const.COLUMN_HEIGHT;
        this.maxNumber = this.maxNumber >= 60 ? 60 : this.maxNumber;
        this.minNumber = this.maxNumber - Const.HEIGHT_MIN;
      } else {
        this.maxNumber = Const.OPACITY_FALSE;
        this.minNumber = Const.OPACITY_FALSE;
      }
      if (this.isListening) {
        animateTo({ duration: Const.ANIMATION_DURATION, curve: Curve.EaseInOut }, () => {
          this.yMax = Math.round(Math.random() * 60);
          this.yMin = Math.round(Math.random() * 20);
        })
      }
    }, Const.SET_INTERVAL_TIME);
  })
  .onActionEnd(() => {
    clearInterval(this.count);
    this.flagInfoOpacity = Const.OPACITY_TRUE;
    this.yMax = Const.OPACITY_FALSE;
    this.yMin = Const.OPACITY_FALSE;
    this.avRecord.stopRecordingProcess();
  })
  • 长按按钮触发 onAction 方法,开始语音录制,设置相关状态,并每隔一段时间获取音频振幅。
  • 长按结束触发 onActionEnd 方法,清除定时器,停止录制。