目标:根据声音的大小实现声音振动特效
实现步骤:
- 通过 getAudioCapturerMaxAmplitude 观察音频区间
- 封装振动组件,通过声音振幅数据实现振动效果
落地代码:
1)获取振幅数据,出入振动组件 AudioPage.ets
timer?: number
@State maxAmplitude: number = 0
// startRecord 4. 每100ms获取一下声音振幅
this.timer = setInterval(async () => {
this.maxAmplitude = await avRecorder.getAudioCapturerMaxAmplitude()
logger.debug('startRecord', this.maxAmplitude.toString())
}, 100)
// stopRecord 清理定时器
clearInterval(this.timer)
AudioBoComp({ maxAmplitude: this.maxAmplitude })
2)实现振动组件 Audio/AudioBoComp.ets
@Component
struct AudioBoComp {
@Prop @Watch('onChange') maxAmplitude: number
@State per: number = 0
onChange() {
animateTo({ duration: 100 }, () => {
if (this.maxAmplitude < 500) {
this.per = 0
} else if (this.maxAmplitude > 30000) {
this.per = 1
} else {
this.per = this.maxAmplitude / 30000
}
})
}
build() {
Row({ space: 5 }) {
ForEach(Array.from({ length: 30 }), () => {
Column()
.layoutWeight(1)
.height(this.per * 100 * Math.random())
.backgroundColor($r('app.color.common_blue'))
})
}
.width('100%')
.height(100)
}
}