<!-- HTML -->
<view @touchstart="voiceStart" @touchmove="voiceMove" @touchend="voiceEnd" >按住 说</view>
//全局方法
const recorderManager = uni.getRecorderManager();
Vue.prototype.$audio = uni.createInnerAudioContext()
//监听
onReady() {
recorderManager.onStop((res) => {
// 如果用户不是想取消就发送, 如是是想取消就重置想取消的状态
if (!this.recall) {
this.recordFire = res
//创建语音消息
this.createVoice()
} else {
this.recall = false
}
})
}
//按住说话
async voiceStart() {
//获取话筒权限
let res = await this.getRecordPermission()
if (res) return;
this.vibrateShort()
this.showVoiceMask = true
this.recording = true
recorderManager.start();
this.durationTimer = setInterval(() => {
this.durationNum += 1
}, 1000)
}
//判断是否取消语音
voiceMove(e) {
this.windowHeight = uni.getSystemInfoSync().windowHeight
this.recall = this.windowHeight - e.touches[0].pageY > 161
},
//松开手指
voiceEnd() {
this.showVoiceMask = false
clearInterval(this.durationTimer)
recorderManager.stop();
},
//播放语音
mounted(){
this.innerAudioContext = uni.createInnerAudioContext();
this.innerAudioContext.src = this.message.remote;
this.innerAudioContext.onCanplay(() => {
console.log('可以播放了', this.innerAudioContext.duration)
this.duration = this.innerAudioContext.duration
})
},
//点击播放 传递事件
playSound() {
this.$emit('play', this.message)
},
//接收事件
play(message) {
if (this.$audio.src === message.remote) {
console.log(message.isPlay)
if (message.isPlay) {
this.$set(message, 'isPlay', false)
this.$audio.pause()
} else {
this.$set(message, 'isPlay', true)
this.$audio.play()
}
} else {
if (this.onPlayMessage) {
this.$set(this.onPlayMessage, 'isPlay', false)
}
this.$audio.src = message.remote;
this.$audio.play()
this.$set(message, 'isPlay', true)
}
this.onPlayMessage = message
}
//监听播放结束
created() {
this.$audio.onEnded(() => {
if (this.onPlayMessage) {
this.onPlayMessage.isPlay = false
//判断是否还有下段录音消息
let index = this.messagelist.findIndex(e => e.messageUId == this.onPlayMessage.messageUId)
let item = this.messagelist.filter((e, i) => {
return i < index && e.messageType == 3
})
if (!item.length) return
let items = item.filter(e => e.senderUserId != this.$store.state.userMeans.uid)
if (!items.length) return
let nextItem = items[items.length - 1]
let nextIndex = this.messagelist.findIndex(e => e.messageId == nextItem.messageId)
this.$refs[`messageItems${nextIndex}`][0].playSound(nextItem)
}
})
},
uniapp 创建语音消息
于 2024-01-27 17:22:10 首次发布