1.首先现将音频听过接口上传到服务器
uni.uploadFile({
url: '',
filePath: this.src,
name: 'file',
fileName: 'mp3',
formData: {
mp3: 'mp3' // 在这里设置名为 MP3 的参数值
},
success: res => {
const responseData = JSON.parse(res.data);
this.uploadinfo = responseData.data
console.log(this.uploadinfo);
let data = {
file: this.uploadinfo,
type: '1'
}
actionExec(data).then(res => {
console.log(res);
this.text = res.data.data
})
},
fail: err => {
console.error('上传失败', err);
}
});
2.上传成功之后,后端接口会返回一个url, 然后开始渲染样式
<view class="audio" v-if="item.video != ''" @click="playbtn(index,item)">
<a-trumpet v-if="item.video != ''" :isPlay="item.isPlay" direction="right"></a-trumpet>
<text class="time" v-if="item.video != ''"> {{nameList[index]}}</text>
</view>
3.利用uni.createInnerAudioContext()获取文件的url进行解析并获取时长
helplist().then(res => {
console.log(res, 'helplist');
if (res.data.code !== 200) return
// this.helpdata = res.data.data
this.helpdata = res.data.data.map(item => {
return {
...item,
isPlay: false
}; // 使用对象展开运算符添加 isPlay 属性
});
console.log(this.helpdata)
this.timeStr = '00:00';
let data = []
let counter = 0;
for (let i = 0; i < this.helpdata.length; i++) {
const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.src = this.helpdata[i].video;
innerAudioContext.onCanplay(() => {
const duration = innerAudioContext.duration;
const timeStr = this.formatTime(duration);
this.$set(this.nameList, i, timeStr); // 使用 $set 方法更新数组中的数据
this.nameList[i] = timeStr; // 将格式化后的时间字符串存储到 nameList 数组中对应位置
counter++;
if (counter === this.helpdata.length) {
console.log('All audio durations fetched and formatted:', this.nameList);
}
});
innerAudioContext.onError((res) => {
// console.error('Error fetching or formatting audio duration:', res.errMsg);
counter++; // 即使出现错误,也需要递增计数器以检查处理完成情况
});
}
console.log(this.helpdata, '==============this.helpdata');
})
4.将获取到的时间进行时间格式处理
```css
//格式化时间格式
formatTime(num) {
num = num.toFixed(0);
let second = num % 60;
if (second < 10) second = '0' + second;
let min = Math.floor(num / 60);
if (min < 10) min = '0' + min;
return min + ":" + second;
},
最后完整的效果就是这样