3. 手势操作处理
PanGesture({ direction: PanDirection.Left | PanDirection.Right | PanDirection.Up, distance: 50 })
.onActionStart((event: GestureEvent) => {
const offsetX = event.offsetX;
const offsetY = event.offsetY;
this.mode = getMode(offsetX, offsetY);
this.updateStateByMode();
})
.onActionUpdate((event: GestureEvent) => {
const offsetX = event.offsetX;
const offsetY = event.offsetY;
this.mode = getMode(offsetX, offsetY);
this.updateStateByMode();
})
.onActionEnd(() => {
this.doGestureEndBusiness();
})
- 利用
PanGesture监听手势操作,根据手势偏移量调用getMode方法确定当前模式。 - 调用
updateStateByMode方法根据不同模式更新组件样式。 - 手势结束调用
doGestureEndBusiness方法处理业务逻辑。
4. 模式状态更新
updateStateByMode(): void {
if (this.mode === Const.VOICE) {
this.backgroundVoice = Color.White;
this.fontColorVoice = Color.Black;
this.waterRipplesBg = $r("app.string.voice_record_water_ripples_bg");
this.fontColorCancel = Color.White;
this.backgroundCancel = Color.Gray;
this.fontColorWord = Color.White;
this.backgroundWord = Color.Gray;
} else if (this.mode === Const.TEXT) {
this.fontColorWord = Color.Black;
this.backgroundWord = Color.White;
this.waterRipplesBg = $r("app.string.voice_record_water_ripples_bg");
this.fontColorCancel = Color.White;
this.backgroundCancel = Color.Gray;
this.backgroundVoice = Color.Gray;
this.fontColorVoice = Color.White;
} else if (this.mode === Const.CANCEL) {
this.fontColorCancel = Color.Black;
this.backgroundCancel = Color.White;
this.waterRipplesBg = $r("app.string.voice_record_water_ripples_bg_over");
this.fontColorWord = Color.White;
this.backgroundWord = Color.Gray;
this.backgroundVoice = Color.Gray;
this.fontColorVoice = Color.White;
}
}
- 根据不同的模式(语音录制、转文字、取消)更新组件的背景颜色、字体颜色等样式。
5. 手势结束业务处理
doGestureEndBusiness(): void {
if (this.mode === Const.VOICE) {
this.timeEnd = Math.floor(new Date().getTime() / Const.ANIMATION_DURATION);
this.timeAv = this.timeEnd - this.timeStart;
this.onSend(new String(this.timeAv).toString(), 2)
} else if (this.mode === Const.TEXT) {
this.onSend('默认文字', 0)
}
this.resetState();
clearInterval(this.count);
this.isListening = false;
animateTo({ duration: Const.OPACITY_FALSE }, () => {
this.yMax = Const.OPACITY_FALSE;
this.yMin = Const.OPACITY_FALSE;
})
this.flagUpOpacity = Const.OPACITY_FALSE;
if (this.mode === Const.VOICE) {
this.flagInfoOpacity = Const.OPACITY_TRUE;
}
this.avRecord.stopRecordingProcess();
}
- 根据不同模式执行相应的业务逻辑,如发送语音时长或默认文字。
- 重置组件状态,停止录制。
总结
通过上述代码实现,我们在 HarmonyOS Next 中完成了一个语音交互组件的开发。该组件支持语音录制、转文字和取消操作,通过手势识别和状态管理实现了良好的交互体验。开发者可以根据实际需求对代码进行扩展和优化,以满足不同应用场景的需求。