uniapp 上传音频并显示音频时长且可以播放

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;
			},

最后完整的效果就是这样
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蒜苔肉丝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值