效果描述
在与好友的聊天对话框页面中点击语音进行播放的时候
如果你先点击了一条语音,此时该条语音开始进行播放,如果在该条语音播放结束之前再次进行点击,那么该条语音的播放就会被暂停,然后再次点击该条语音,此时该条语音就会从上次播放终端的位置继续开始播放;
如果在该条语音播放完毕之后再次点击该条语音,则该条语音将从头进行播放;
如果你在该条语音播放播放过程中或者该条语音播放完毕之后,点击了另一条语音,那么将会从头播放你刚才点击的那条语音。
对话框页面展示
代码实现
渲染层
<view class="message" v-if="item.textType == 2" @click="playVoice(item.msgText.voice)">
<!-- 音频 -->
<view class="msg-text voice" :style="{width:item.msgText.time*4+'rpx'}">
{
{item.msgText.time}}″
// 当前语音正在播放
<image v-if="currentSrc==item.msgText.voice&&palying" src="/static/message/voice_gif.gif"
class="voice-img" mode="aspectFit"></image>
// 当前语音没有被播放
<image v-else src="/static/message/voice.svg" class="voice-img" mode="aspectFit"></image>
</view>
</view>
逻辑层
//音频播放
const innerAudioContext = uni.createInnerAudioContext();
const palying = ref(false)
const currentSrc = ref('')
// 播放语音
const playVoice = (e) => {
console.log("点击播放按钮", e, currentSrc.value)
// 如果点击的是当前正在播放的音频,则切换播放/暂停状态
if (currentSrc.value == e) {
console.log("点击的是当前正在播放的音频")
if (innerAudioContext.paused) {
innerAudioContext.play();
} else {
innerAudioContext.pause();
}
palying.value = !palying.value;
} else {
console.log("当前点击的是不同的音频", innerAudioContext.src, e, )
// 如果点击的是不同的音频,停止当前播放的音频并从头播放新的音频
if (innerAudioContext.src != e) {
innerAudioContext.offEnded();
innerAudioContext.stop();
innerAudioContext.src = e;
innerAudioContext.autoplay = true;
innerAudioContext.play();
currentSrc.value = e; // 更新当前播放的音频源
palying.value = true;
}
}
// 监听播放结束事件
innerAudioContext.onEnded(() => {
console.log('播放结束');
palying.value = false;
// currentSrc.value = null; // 清除当前播放的音频源
innerAudioContext.seek(0) //将播放位置重置到开头
});
}
语音消息格式
{
id: 3,
"sendName": "゛时光い",
"receviceName": "xpq",
"msgSendHeadImg": "https://profile-avatar.csdnimg.cn/d29edf7348024b8f834e7a8b90887173_qq_45569925.jpg!1",
"msgSendId": 1,
"msgText": {
"voice": "https://web-ext-storage.dcloud.net.cn/uni-app/ForElise.mp3",
"time": 175 //秒
},
"createTime": "2022-01-06 12:22:12",
"updateTime": null,
"chatmState": 1,
"TextType": 2
},