我写个HarmonyOS Next版本的微信聊天02

简介: 我写个HarmonyOS Next版本的微信聊天02

按住说话

0009fc57aa131188fd48765522a8280a.png

定义是否正在说话的变量


// 按住说话 录音模态
  @State
  showTalkContainer: boolean = false

注册触摸事件 Touch

长按 按住说话时触发, Touch事件是会持续触发的,通过判断 event.type 来获知 触摸状态

  1. down 按下
  2. move 移动
  3. up 松开


Button("按住说话")
    .layoutWeight(1)
    .type(ButtonType.Normal)
    .borderRadius(5)
    .backgroundColor("#fff")
    .fontColor("#000")
    .onTouch(this.onPressTalk)

定义 this.onPressTalk


// 按住说话 持续触发
  onPressTalk = async (event: TouchEvent) => {
    if (event.type === TouchType.Down) {
      // 按下
      this.showTalkContainer = true
    } else if (event.type === TouchType.Up) {
      // 松开手
      this.showTalkContainer = false
    }
  }

实现全屏遮罩效果

该效果利用鸿蒙应用中的全模态实现 bindContentCover

给组件绑定全屏模态页面,点击后显示模态页面。模态页面内容自定义,显示方式可设置无动画过渡,上下切换过渡以及透明渐变过渡方式。

this.talkContainerBuilder 为全模态出现时对应的内容布局,它是一个自定义构建函数


Button("按住说话")
    .layoutWeight(1)
    .type(ButtonType.Normal)
    .borderRadius(5)
    .backgroundColor("#fff")
    .fontColor("#000")
    .bindContentCover($$this.showTalkContainer, this.talkContainerBuilder,
      { modalTransition: ModalTransition.NONE })
    .onTouch(this.onPressTalk)

定义this.talkContainerBuilder

// 正在说话 页面布局
  @Builder
  talkContainerBuilder() {
    Column() {
      //   1 中心的提示   
      Row() {
        Text()
          .width(10)
          .height(10)
          .backgroundColor("#95EC6A")
          .position({
            bottom: -5,
            left: "50%"
          })
          .translate({
            x: "-50%"
          })
          .rotate({
            angle: 45
          })
      }
      .width("50%")
      .height(80)
      .backgroundColor("#95EC6A")
      .position({
        top: "40%",
        left: "50%"
      })
      .translate({
        x: "-50%"
      })
      .borderRadius(10)
      .justifyContent(FlexAlign.Center)
      .alignItems(VerticalAlign.Center)
      //   2 取消和转文字
      Row() {
        Row() {
          Text("X")
            .fontSize(20)
            .width(60)
            .height(60)
            .borderRadius(30)
            .fontColor("#000")
            .backgroundColor("#fff")
            .textAlign(TextAlign.Center)
            .align(Alignment.Center)
            .fontColor("#ccc")
            .id("aabb")
            .rotate({ angle: -20 })
        }
        Row() {
          Text("文")
            .fontSize(20)
            .width(60)
            .height(60)
            .borderRadius(30)
            .fontColor("#ccc")
            .backgroundColor("#333")
            .textAlign(TextAlign.Center)
            .align(Alignment.Center)
            .id("ddee")
            .rotate({ angle: 20 })
        }
        // 3  松开发送
        Text("松开发送")
          .fontColor("#fff")
          .width("100%")
          .position({
            bottom: 0,
            left: 0
          })
          .textAlign(TextAlign.Center)
      }
      .width("100%")
      .position({
        bottom: "23%"
      })
      .justifyContent(FlexAlign.SpaceBetween)
      .padding({
        left: 60, right: 60
      })
      //   4 底部白色大球
      Row() {
      }
      .width(600)
      .height(600)
      .backgroundColor("#fff")
      .position({
        bottom: 0,
        left: "50%"
      })
      .translate({
        x: "-50%",
        y: "70%"
      })
      .borderRadius("50%")
    }
    .width("100%")
    .height("100%")
    .backgroundColor("rgba(0,0,0,0.5)")
  }

说话声纹

这个绿色容器中的波纹,是通过canva来描述的,真正的逻辑应该是监听或者获取当前声音音量的大小,然后根据它转换对应的波纹。但是没有在鸿蒙中直接找到api,查阅资料发现需要自己分析音频文件数据,自己转化才可以,时间关系就没有继续往下实现。使用随机数简单模拟了下。

配置 CanvasRenderingContext2D 对象的参数

//用来配置 CanvasRenderingContext2D 对象的参数,包括是否开启抗锯齿,true表明开启抗锯齿。
  settings: RenderingContextSettings = new RenderingContextSettings(true)

用来创建CanvasRenderingContext2D对象

//用来创建CanvasRenderingContext2D对象,通过在canvas中调用CanvasRenderingContext2D对象来绘制。
  context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)

定义声纹自定义构建函数

这里使用canvas画布技术,在onReady 生命周期函数中 通过开启一个定时器,在定时器中不断重复以下过程

  1. 通过clearRect 清空上一次描绘的波纹
  2. 通过 fillRect 随机描绘这一次的波纹

最后,如果此组件被销毁了,可以在 onDisAppear 中停止定时器


/**
   * 录音中的 动态声纹波浪
   */
  @Builder
  vocalPrint() {
    Canvas(this.context)
      .onDisAppear(() => {
        clearInterval(this.voiceTimeId)
      })
      .width('80%')
      .height('80%')
      .onReady(() => {
        //可以在这里绘制内容。
        clearInterval(this.voiceTimeId)
        this.voiceTimeId = setInterval(() => {
          this.context.clearRect(0, 0, 1000, 1000)
          for (let index = 0; index < 35; index++) {
            const random = Math.floor(Math.random() * 10)
            let height = 20 + random
            this.context.fillRect(0 + index * 5, 32 - height / 2, 2, height);
          }
        }, 100)
      })
  }

使用声纹构造函数

发送信息-取消发送

93829b698399abeb78efb5d4b5be3993.png

这部分的UI交互相对来说比较复杂,当按住 按住说话 时:

  1. 手指移动到 X, 表示取消发送
  2. 手指移动到,表示转换文字
  3. 手指直接松开时,发送录音

这部分功能的核心思想时,检测手指是否移动到了相应的元素,触发对应的业务逻辑即可。但是现实的问题是,找不到合适的事件,比如元素引入事件,所以后期采取的是检测手指在整个屏幕的坐标是否触及到了 X 来实现。

定义长按状态的枚举

  1. 没有长按
  2. 长按
  3. 长按-X
  4. 长按-


enum PressCancelVoicePostText {
  // 没有长按
  none = 0,
  //   长按 没有选中“取消发送”或者"转语音"
  presssing = 1,
  //   取消发送
  cancelVoice = 2,
  //   转文字
  postText = 3
}

定义手指坐标类型


/**
 * 长按时,手指的坐标
 */
interface ScreenOffset {
  x: number
  y: number
  width: number
  height: number
}

定义长按状态


// 长按状态
@State
pressCancelVoicePostText: PressCancelVoicePostText = PressCancelVoicePostText.none

定义 X 和 文的坐标状态


// “x ”的坐标
  xScreenOffset: ScreenOffset = {
    x: 0,
    y: 0,
    width: 0,
    height: 0
  }
  TextScreenOffset: ScreenOffset = {
    x: 0,
    y: 0,
    width: 0,
    height: 0
  }

实时获取 X 和 文 的坐标

在组件中监听 onAppear 事件,根据组件的唯一标识id来获取坐标数据

X
Text("X")
            .fontSize(20)
            .width(60)
            .height(60)
            .borderRadius(30)
            .fontColor(this.pressCancelVoicePostText === PressCancelVoicePostText.cancelVoice ? "#000" : "#ccc")
            .backgroundColor(this.pressCancelVoicePostText === PressCancelVoicePostText.cancelVoice ? "#fff" : "#333")
            .textAlign(TextAlign.Center)
            .align(Alignment.Center)
            .fontColor("#ccc")
            .id("aabb")
            .rotate({ angle: -20 })
            .onAppear(() => {
              let modePosition: componentUtils.ComponentInfo = componentUtils.getRectangleById("aabb");
              this.xScreenOffset.x = px2vp(modePosition.screenOffset.x)
              this.xScreenOffset.y = px2vp(modePosition.screenOffset.y)
              this.xScreenOffset.width = px2vp(modePosition.size.width)
              this.xScreenOffset.height = px2vp(modePosition.size.height)
            })


Text("文")
            .fontSize(20)
            .width(60)
            .height(60)
            .borderRadius(30)
            .fontColor(this.pressCancelVoicePostText === PressCancelVoicePostText.postText ? "#000" : "#ccc")
            .backgroundColor(this.pressCancelVoicePostText === PressCancelVoicePostText.postText ? "#fff" : "#333")
            .textAlign(TextAlign.Center)
            .align(Alignment.Center)
            .id("ddee")
            .rotate({ angle: 20 })
            .onAppear(() => {
              let modePosition: componentUtils.ComponentInfo = componentUtils.getRectangleById("ddee");
              // px单位
              this.TextScreenOffset.x = px2vp(modePosition.screenOffset.x)
              this.TextScreenOffset.y = px2vp(modePosition.screenOffset.y)
              this.TextScreenOffset.width = px2vp(modePosition.size.width)
              this.TextScreenOffset.height = px2vp(modePosition.size.height)
            })

调整touch事件onPressTalk的逻辑

该函数的调整逻辑是 判断当前手指的坐标是否触碰到了 X 或者 , 然后设置对应的状态


// 按住说话 持续触发
  onPressTalk = async (event: TouchEvent) => {
    if (event.type === TouchType.Down) {
      // 手指按下时触发
      this.pressCancelVoicePostText = PressCancelVoicePostText.presssing
      // 按下
      this.showTalkContainer = true
    } else if (event.type === TouchType.Move) {
      // 手指移动时持续触发
      this.pressCancelVoicePostText = PressCancelVoicePostText.presssing
      // 获取当前手指的坐标
      const x = event.touches[0].displayX
      const y = event.touches[0].displayY
      // 判断是否碰到了 “X”
      let isTouchX = this.xScreenOffset.x <= x && this.xScreenOffset.x + this.xScreenOffset.width >= x &&
        this.xScreenOffset.y <= y && this.xScreenOffset.y + this.xScreenOffset.width >= y
      // 判断是否碰到了 "文"
      let isTouchText = this.TextScreenOffset.x <= x && this.TextScreenOffset.x + this.TextScreenOffset.width >= x &&
        this.TextScreenOffset.y <= y && this.TextScreenOffset.y + this.TextScreenOffset.width >= y
      if (isTouchX) {
        // 取消发送
        this.pressCancelVoicePostText = PressCancelVoicePostText.cancelVoice
      } else if (isTouchText) {
        // 转换文字
        this.pressCancelVoicePostText = PressCancelVoicePostText.postText
      }
    } else if (event.type === TouchType.Up) {
      // 松开手
      this.showTalkContainer = false
      if (this.pressCancelVoicePostText === PressCancelVoicePostText.postText) {
        // 转换文字
      } else if (this.pressCancelVoicePostText === PressCancelVoicePostText.cancelVoice) {
        // 取消发送
      } else {
        // 发送录音
      }
    }
  }

添加 X 和 文字的 样式

this.pressCancelVoicePostText 状态发生改变时,需要调整 对应的组件的样式


调整声纹容器的样式

8e252acab4015b3f106b2de1003b216c.png

  1. 如果当前正在录音,显示正常绿色的声纹
  2. 如果当前取消发送,显示取消红色的声纹
  3. 如果当前转换文字,显示绿色的空的内容-后期存放实时的语音转换的文字
//   1 中心的提示   显示波浪线
      Row() {
        if (this.pressCancelVoicePostText !== PressCancelVoicePostText.postText) {
          // 声纹
          this.vocalPrint()
        } else {
          Scroll() {
            // 显示录音的文字
            Text("")
              .fontSize(12)
              .fontColor("#666")
          }
          .width("100%")
          .height("100%")
        }
        Text()
          .width(10)
          .height(10)
          .backgroundColor(this.pressCancelVoicePostText === PressCancelVoicePostText.cancelVoice ? Color.Red :
            "#95EC6A")
          .position({
            bottom: -5,
            left: "50%"
          })
          .translate({
            x: "-50%"
          })
          .rotate({
            angle: 45
          })
      }
      .width("50%")
      .height(80)
      .backgroundColor(this.pressCancelVoicePostText === PressCancelVoicePostText.cancelVoice ? Color.Red : "#95EC6A")
      .position({
        top: "40%",
        left: "50%"
      })
      .translate({
        x: "-50%"
      })
      .borderRadius(10)
      .justifyContent(FlexAlign.Center)
      .alignItems(VerticalAlign.Center)

完整代码

/**
 * 当前输入状态 语音或者文本
 */
import { componentUtils } from '@kit.ArkUI'
enum WXInputType {
  /**
   * 语音输入
   */
  voice = 0,
  /**
   * 文本输入
   */
  text = 1
}
enum MessageType {
  /**
   * 声音
   */
  voice = 0,
  /**
   * 文本
   */
  text = 1
}
// 消息
class ChatMessage {
  /**
   * 消息类型:【录音、文本】
   */
  type: MessageType
  /**
   * 内容 [录音-文件路径,文本-内容]
   */
  content: string
  /**
   * 消息时间
   */
  time: string
  /**
   * 声音的持续时间 单位毫秒
   */
  duration?: number
  /**
   * 录音转的文字
   */
  translateText?: string
  /**
   * 是否显示转好的文字
   */
  isShowTranslateText: boolean = false
  constructor(type: MessageType, content: string, duration?: number, translateText?: string) {
    this.type = type
    this.content = content
    const date = new Date()
    this.time = `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    this.duration = duration
    this.translateText = translateText
  }
}
enum PressCancelVoicePostText {
  // 没有长按
  none = 0,
  //   长按 没有选中“取消发送”或者"转语音"
  presssing = 1,
  //   取消发送
  cancelVoice = 2,
  //   转文字
  postText = 3
}
/**
 * 长按时,手指的坐标
 */
interface ScreenOffset {
  x: number
  y: number
  width: number
  height: number
}
@Entry
@Component
struct Index {
  // 状态栏高度
  @StorageProp("vpHeight")
  vpHeight: number = 0
  // 输入框内容
  @State
  textValue: string = ""
  // 输入状态 语音或者文字
  @State
  inputType: WXInputType = WXInputType.voice
  // 消息
  @State
  chatList: ChatMessage[] = []
  // 按住说话 录音模态
  @State
  showTalkContainer: boolean = false
  // 长按状态
  @State
  pressCancelVoicePostText: PressCancelVoicePostText = PressCancelVoicePostText.none
  //用来配置 CanvasRenderingContext2D 对象的参数,包括是否开启抗锯齿,true表明开启抗锯齿。
  settings: RenderingContextSettings = new RenderingContextSettings(true)
  //用来创建CanvasRenderingContext2D对象,通过在canvas中调用CanvasRenderingContext2D对象来绘制。
  context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  // 声明波纹定时器id
  voiceTimeId: number = -1
  // “x ”的坐标
  xScreenOffset: ScreenOffset = {
    x: 0,
    y: 0,
    width: 0,
    height: 0
  }
  TextScreenOffset: ScreenOffset = {
    x: 0,
    y: 0,
    width: 0,
    height: 0
  }
  // 发送文本消息
  sendTextMessage = () => {
    if (!this.textValue.trim()) {
      return
    }
    const chat = new ChatMessage(MessageType.text, this.textValue.trim())
    this.chatList.push(chat)
    this.textValue = ""
  }
  // 按住说话 持续触发
  onPressTalk = async (event: TouchEvent) => {
    if (event.type === TouchType.Down) {
      // 手指按下时触发
      this.pressCancelVoicePostText = PressCancelVoicePostText.presssing
      // 按下
      this.showTalkContainer = true
    } else if (event.type === TouchType.Move) {
      // 手指移动时持续触发
      this.pressCancelVoicePostText = PressCancelVoicePostText.presssing
      // 获取当前手指的坐标
      const x = event.touches[0].displayX
      const y = event.touches[0].displayY
      // 判断是否碰到了 “X”
      let isTouchX = this.xScreenOffset.x <= x && this.xScreenOffset.x + this.xScreenOffset.width >= x &&
        this.xScreenOffset.y <= y && this.xScreenOffset.y + this.xScreenOffset.width >= y
      // 判断是否碰到了 "文"
      let isTouchText = this.TextScreenOffset.x <= x && this.TextScreenOffset.x + this.TextScreenOffset.width >= x &&
        this.TextScreenOffset.y <= y && this.TextScreenOffset.y + this.TextScreenOffset.width >= y
      if (isTouchX) {
        // 取消发送
        this.pressCancelVoicePostText = PressCancelVoicePostText.cancelVoice
      } else if (isTouchText) {
        // 转换文字
        this.pressCancelVoicePostText = PressCancelVoicePostText.postText
      }
    } else if (event.type === TouchType.Up) {
      // 松开手
      this.showTalkContainer = false
      if (this.pressCancelVoicePostText === PressCancelVoicePostText.postText) {
        // 转换文字
      } else if (this.pressCancelVoicePostText === PressCancelVoicePostText.cancelVoice) {
        // 取消发送
      } else {
        // 发送录音
      }
    }
  }
  build() {
    Column() {
      // 1 顶部标题栏
      Row() {
        Image($r("app.media.left"))
          .width(25)
        Text("kto卋讓硪玩孫悟空")
        Image($r("app.media.more"))
          .width(25)
      }
      .width("100%")
      .justifyContent(FlexAlign.SpaceBetween)
      .border({
        width: {
          bottom: 1
        },
        color: "#ddd"
      })
      .padding(10)
      .expandSafeArea([SafeAreaType.KEYBOARD], [SafeAreaEdge.BOTTOM])
      //   2 聊天滚动容器
      Scroll() {
        Column({ space: 10 }) {
          ForEach(this.chatList, (item: ChatMessage, index: number) => {
            if (item.type === MessageType.text) {
              this.chatTextBuilder(item.content, item.time)
            }
          })
        }.width("100%")
        .padding(10)
        .justifyContent(FlexAlign.Start)
      }
      .layoutWeight(1)
      .align(Alignment.Top)
      .expandSafeArea([SafeAreaType.KEYBOARD], [SafeAreaEdge.BOTTOM])
      //   3 底部聊天发送框
      Row({ space: 5 }) {
        if (WXInputType.text === this.inputType) {
          Image($r("app.media.voice"))
            .width(40)
            .fillColor("#333")
            .borderRadius(20)
            .border({ width: 2 })
            .onClick(() => {
              this.inputType = WXInputType.voice
            })
          TextInput({ text: $$this.textValue })
            .onAppear(() => {
              // 自动显示焦点
              this.getUIContext().getFocusController().requestFocus("textinput1")
            })
            .layoutWeight(1)
            .backgroundColor("#fff")
            .borderRadius(3)
            .defaultFocus(true)
            .id("textinput1")
        } else if (WXInputType.voice === this.inputType) {
          Image($r("app.media.keyboard"))
            .width(40)
            .fillColor("#333")
            .borderRadius(20)
            .border({ width: 2 })
            .onClick(() => {
              this.inputType = WXInputType.text
            })
          Button("按住说话")
            .layoutWeight(1)
            .type(ButtonType.Normal)
            .borderRadius(5)
            .backgroundColor("#fff")
            .fontColor("#000")
            .bindContentCover($$this.showTalkContainer, this.talkContainerBuilder,
              { modalTransition: ModalTransition.NONE })
            .onTouch(this.onPressTalk)
        }
        Image($r("app.media.smile"))
          .width(40)
          .fillColor("#333")
        if (this.textValue.length) {
          Button("发送")
            .backgroundColor("#08C060")
            .type(ButtonType.Normal)
            .fontColor("#fff")
            .borderRadius(5)
            .onClick(this.sendTextMessage)
        } else {
          Image($r("app.media.plus"))
            .width(48)
            .fillColor("#333")
        }
      }
      .width("100%")
      .padding(10)
      .backgroundColor("#F7F7F7")
    }
    .height('100%')
    .width('100%')
    .backgroundColor("#EDEDED")
    .backgroundImageSize(ImageSize.Cover)
    .padding({
      top: this.vpHeight + 20
    })
  }
  // 文字消息
  @Builder
  chatTextBuilder(text: string, time: string) {
    Column({ space: 5 }) {
      Text(time)
        .width("100%")
        .textAlign(TextAlign.Center)
        .fontColor("#666")
        .fontSize(14)
      Row() {
        Flex({ justifyContent: FlexAlign.End }) {
          Row() {
            Text(text)
              .padding(11);
            Text()
              .width(10)
              .height(10)
              .backgroundColor("#93EC6C")
              .position({
                right: 0,
                top: 15
              })
              .translate({
                x: 5,
              })
              .rotate({
                angle: 45
              });
          }
          .backgroundColor("#93EC6C")
          .margin({ right: 15 })
          .borderRadius(5);
          Image($r("app.media.avatar"))
            .width(40)
            .aspectRatio(1);
        }
        .width("100%");
      }
      .width("100%")
      .padding({
        left: 40
      })
      .justifyContent(FlexAlign.End)
    }
    .width("100%")
  }
  // 正在说话 页面布局
  @Builder
  talkContainerBuilder() {
    Column() {
      //   1 中心的提示   显示波浪线
      Row() {
        if (this.pressCancelVoicePostText !== PressCancelVoicePostText.postText) {
          // 声纹
          this.vocalPrint()
        } else {
          Scroll() {
            // 显示录音的文字
            Text("")
              .fontSize(12)
              .fontColor("#666")
          }
          .width("100%")
          .height("100%")
        }
        Text()
          .width(10)
          .height(10)
          .backgroundColor(this.pressCancelVoicePostText === PressCancelVoicePostText.cancelVoice ? Color.Red :
            "#95EC6A")
          .position({
            bottom: -5,
            left: "50%"
          })
          .translate({
            x: "-50%"
          })
          .rotate({
            angle: 45
          })
      }
      .width("50%")
      .height(80)
      .backgroundColor(this.pressCancelVoicePostText === PressCancelVoicePostText.cancelVoice ? Color.Red : "#95EC6A")
      .position({
        top: "40%",
        left: "50%"
      })
      .translate({
        x: "-50%"
      })
      .borderRadius(10)
      .justifyContent(FlexAlign.Center)
      .alignItems(VerticalAlign.Center)
      //   2 取消和转文字
      Row() {
        Row() {
          Text("X")
            .fontSize(20)
            .width(60)
            .height(60)
            .borderRadius(30)
            .fontColor(this.pressCancelVoicePostText === PressCancelVoicePostText.cancelVoice ? "#000" : "#ccc")
            .backgroundColor(this.pressCancelVoicePostText === PressCancelVoicePostText.cancelVoice ? "#fff" : "#333")
            .textAlign(TextAlign.Center)
            .align(Alignment.Center)
            .fontColor("#ccc")
            .id("aabb")
            .rotate({ angle: -20 })
            .onAppear(() => {
              let modePosition: componentUtils.ComponentInfo = componentUtils.getRectangleById("aabb");
              this.xScreenOffset.x = px2vp(modePosition.screenOffset.x)
              this.xScreenOffset.y = px2vp(modePosition.screenOffset.y)
              this.xScreenOffset.width = px2vp(modePosition.size.width)
              this.xScreenOffset.height = px2vp(modePosition.size.height)
            })
        }
        Row() {
          Text("文")
            .fontSize(20)
            .width(60)
            .height(60)
            .borderRadius(30)
            .fontColor(this.pressCancelVoicePostText === PressCancelVoicePostText.postText ? "#000" : "#ccc")
            .backgroundColor(this.pressCancelVoicePostText === PressCancelVoicePostText.postText ? "#fff" : "#333")
            .textAlign(TextAlign.Center)
            .align(Alignment.Center)
            .id("ddee")
            .rotate({ angle: 20 })
            .onAppear(() => {
              let modePosition: componentUtils.ComponentInfo = componentUtils.getRectangleById("ddee");
              // px单位
              this.TextScreenOffset.x = px2vp(modePosition.screenOffset.x)
              this.TextScreenOffset.y = px2vp(modePosition.screenOffset.y)
              this.TextScreenOffset.width = px2vp(modePosition.size.width)
              this.TextScreenOffset.height = px2vp(modePosition.size.height)
            })
        }
        // 3  松开发送
        Text(this.pressCancelVoicePostText === PressCancelVoicePostText.cancelVoice ? '取消发送' :
          (this.pressCancelVoicePostText === PressCancelVoicePostText.postText ? '转换文字' : "松开发送"))
          .fontColor("#fff")
          .width("100%")
          .position({
            bottom: 0,
            left: 0
          })
          .textAlign(TextAlign.Center)
      }
      .width("100%")
      .position({
        bottom: "23%"
      })
      .justifyContent(FlexAlign.SpaceBetween)
      .padding({
        left: 60, right: 60
      })
      //   4 底部白色大球
      Row() {
      }
      .width(600)
      .height(600)
      .backgroundColor("#fff")
      .position({
        bottom: 0,
        left: "50%"
      })
      .translate({
        x: "-50%",
        y: "70%"
      })
      .borderRadius("50%")
    }
    .width("100%")
    .height("100%")
    .backgroundColor("rgba(0,0,0,0.5)")
  }
  /**
   * 录音中的 动态声纹波浪
   */
  @Builder
  vocalPrint() {
    Canvas(this.context)
      .onDisAppear(() => {
        clearInterval(this.voiceTimeId)
      })
      .width('80%')
      .height('80%')
      .onReady(() => {
        //可以在这里绘制内容。
        clearInterval(this.voiceTimeId)
        this.voiceTimeId = setInterval(() => {
          this.context.clearRect(0, 0, 1000, 1000)
          for (let index = 0; index < 35; index++) {
            const random = Math.floor(Math.random() * 10)
            let height = 20 + random
            this.context.fillRect(0 + index * 5, 32 - height / 2, 2, height);
          }
        }, 100)
      })
  }
}

总结

一、清晰的枚举定义

代码中使用枚举类型WXInputTypeMessageType分别明确了当前输入状态(语音或文本)以及消息类型,使得代码的可读性和可维护性大大增强。这种方式可以避免使用魔法数字,让开发者更容易理解代码的意图。

二、面向对象的消息类设计

定义了ChatMessage类来表示消息,清晰地封装了消息的各种属性,如消息类型、内容、时间、持续时间、录音转文字结果以及是否显示转好的文字等。这种面向对象的设计方式使得消息的处理更加模块化,方便在不同的地方进行复用和管理。

三、丰富的交互处理

  1. 通过对触摸事件的处理,实现了按住说话的功能。在手指按下、移动和抬起时分别进行不同的状态判断和操作,包括判断是否碰到 “取消发送” 或 “转文字” 的区域,并根据不同状态进行相应的处理。
  2. 底部聊天发送框根据输入状态动态切换显示内容,当输入类型为文本时显示文本输入相关的组件,当为语音时显示按住说话的按钮等,为用户提供了灵活的输入方式选择。

四、强大的页面构建和布局

  1. 使用build方法构建页面结构,清晰地划分了顶部标题栏、聊天滚动容器和底部聊天发送框等部分,通过ColumnRow的组合以及各种属性设置,实现了美观且合理的页面布局。
  2. 在消息显示部分,通过chatTextBuilder方法构建文字消息的布局,包括时间显示、文本内容、背景颜色和图标等,使得消息展示更加清晰美观。
  3. talkContainerBuilder方法构建了按住说话时的页面布局,包括声纹显示、取消和转文字按钮以及底部白色大球等元素,为用户提供了直观的交互界面。

五、动态声纹效果实现

通过vocalPrint方法利用Canvas绘制动态声纹波浪,在录音过程中通过定时器不断更新画布内容,实现了生动的声纹效果,增强了用户体验。

目录
相关文章
|
2月前
|
编解码 API 数据安全/隐私保护
自学HarmonyOS Next记录:实现相册访问功能
最近我决定开发一个鸿蒙App,旨在提供更好的照片管理体验。通过使用PhotoAccessHelper API,我实现了访问、显示和管理设备相册中的照片。过程中遇到了权限不足的问题,通过在config.json中添加权限声明并编写权限检查代码得以解决。此外,我还实现了分页加载和展示照片详细信息等功能,提升了用户体验。这次开发不仅让我掌握了API的使用,也深刻体会到鸿蒙系统对用户隐私和数据安全的重视。 总结这次开发,我不仅学到了技术知识,还明白了开发者保护用户数据安全的责任。未来将继续探索更多功能,欢迎关注和收藏!
183 70
自学HarmonyOS Next记录:实现相册访问功能
|
2月前
【HarmonyOS Next开发】:ListItemGroup使用
通过使用ListItemGroup和AlphabetIndexer两种类型组件,实现带标题分类和右侧导航栏的页面
129 61
【HarmonyOS Next开发】:ListItemGroup使用
|
2月前
|
安全 数据安全/隐私保护 Android开发
HarmonyOS 5.0 Next实战应用开发—‘我的家乡’【HarmonyOS Next华为公司完全自研的操作系统】
HarmonyOS NEXT是华为自研的鸿蒙操作系统的重要版本更新,标志着鸿蒙系统首次完全脱离Linux内核及安卓开放源代码项目(AOSP),仅支持鸿蒙内核和鸿蒙系统的应用。该版本引入了“和谐美学”设计理念,通过先进的物理渲染引擎还原真实世界的光影色彩,为用户带来沉浸式体验。应用图标设计融合国画理念,采用留白和实时模糊技术展现中式美学。 HarmonyOS NEXT强化了设备间的协同能力,支持无缝切换任务,如在手机、平板或电脑间继续阅读文章或编辑文件。系统注重数据安全和隐私保护,提供数据加密和隐私权限管理功能。此外,它利用分布式技术实现跨设备资源共
130 15
HarmonyOS 5.0 Next实战应用开发—‘我的家乡’【HarmonyOS Next华为公司完全自研的操作系统】
|
2月前
|
存储 JavaScript 开发工具
基于HarmonyOS 5.0(NEXT)与SpringCloud架构的跨平台应用开发与服务集成研究【实战】
本次的.HarmonyOS Next ,ArkTS语言,HarmonyOS的元服务和DevEco Studio 开发工具,为开发者提供了构建现代化、轻量化、高性能应用的便捷方式。这些技术和工具将帮助开发者更好地适应未来的智能设备和服务提供方式。
67 8
基于HarmonyOS 5.0(NEXT)与SpringCloud架构的跨平台应用开发与服务集成研究【实战】
|
25天前
|
存储 JSON 区块链
【HarmonyOS NEXT开发——ArkTS语言】购物商城的实现【合集】
HarmonyOS应用开发使用@Component装饰器将Home结构体标记为一个组件,意味着它可以在界面构建中被当作一个独立的UI单元来使用,并且按照其内部定义的build方法来渲染具体的界面内容。txt:string定义了一个名为Data的接口,用于规范表示产品数据的结构。src:类型为,推测是用于引用资源(可能是图片资源等)的一种特定类型,用于指定产品对应的图片资源。txt:字符串类型,用于存放产品的文字描述,比如产品名称等相关信息。price:数值类型,用于表示产品的价格信息。
42 5
|
2月前
|
安全 API 数据安全/隐私保护
自学记录HarmonyOS Next DRM API 13:构建安全的数字内容保护系统
在完成HarmonyOS Camera API开发后,我深入研究了数字版权管理(DRM)技术。最新DRM API 13提供了强大的工具,用于保护数字内容的安全传输和使用。通过学习该API的核心功能,如获取许可证、解密内容和管理权限,我实现了一个简单的数字视频保护系统。该系统包括初始化DRM模块、获取许可证、解密视频并播放。此外,我还配置了开发环境并实现了界面布局。未来,随着数字版权保护需求的增加,DRM技术将更加重要。如果你对这一领域感兴趣,欢迎一起探索和进步。
87 18
|
25天前
|
开发工具 开发者 容器
【HarmonyOS NEXT开发——ArkTS语言】欢迎界面(启动加载页)的实现【合集】
从ArkTS代码架构层面而言,@Entry指明入口、@Component助力复用、@Preview便于预览,只是初窥门径,为开发流程带来些许便利。尤其动画回调与Blank组件,细节粗糙,后续定当潜心钻研,力求精进。”,字体颜色为白色,字体大小等设置与之前类似,不过动画配置有所不同,时长为。,不过这里没有看到额外的动画效果添加到这个特定的图片元素上(与前面带动画的元素对比而言)。这是一个显示文本的视图,文本内容为“奇怪的知识”,设置了字体颜色为灰色(的结构体,它代表了整个界面组件的逻辑和视图结构。
40 1
|
2月前
|
人工智能 自然语言处理 API
自学记录HarmonyOS Next的HMS AI API 13:语音合成与语音识别
在完成图像处理项目后,我计划研究HarmonyOS Next API 13中的AI语音技术,包括HMS AI Text-to-Speech和Speech Recognizer。这些API提供了强大的语音合成与识别功能,支持多语言、自定义语速和音调。通过这些API,我将开发一个支持语音输入与输出的“语音助手”原型应用,实现从语音指令解析到语音响应的完整流程。此项目不仅提高了应用的交互性,也为开发者提供了广阔的创新空间。未来,语音技术将在无障碍应用和智慧城市等领域展现巨大潜力。如果你也对语音技术感兴趣,不妨一起探索这个充满无限可能的领域。 (238字符)
102 11
|
2月前
|
存储 API 计算机视觉
自学记录HarmonyOS Next Image API 13:图像处理与传输的开发实践
在完成数字版权管理(DRM)项目后,我决定挑战HarmonyOS Next的图像处理功能,学习Image API和SendableImage API。这两个API支持图像加载、编辑、存储及跨设备发送共享。我计划开发一个简单的图像编辑与发送工具,实现图像裁剪、缩放及跨设备共享功能。通过研究,我深刻体会到HarmonyOS的强大设计,未来这些功能可应用于照片编辑、媒体共享等场景。如果你对图像处理感兴趣,不妨一起探索更多高级特性,共同进步。
78 11
|
2月前
|
传感器 测试技术 定位技术
HarmonyOS Next 模拟器安装与探索
HarmonyOS 5 的发布带来了许多新特性,尤其是 HarmonyOS Next 模拟器。本文将带你一步步了解如何安装和使用这个强大的工具,帮助你更好地进行开发,加速项目进展。通过 DevEco Studio 的 Device Manager,你可以轻松创建、配置并启动模拟器,模拟真实设备的效果,支持多窗口、跨设备测试等新特性。此外,模拟器还提供了虚拟传感器、GPS 模拟、音频输入等功能,极大地方便了开发和调试过程。掌握这些功能,能让你的开发更加高效便捷。
162 9

热门文章

最新文章