uniapp 上传音频(H5可以App不行),并播放后端返回的音频

该代码示例展示了在uni-app框架下如何实现音频文件的选择上传以及播放功能。用户可以选择.m4a或.mp3格式的文件,上传到指定URL,同时支持播放已上传的音频文件,包括播放、暂停、进度控制等操作。
摘要由CSDN通过智能技术生成

1.上传

record() {
				let _this = this
				uni.chooseFile({
					count: 1, //默认100
					extension: ['.m4a', '.mp3'], //根据文件拓展名过滤,每一项都不能是空字符串。默认不过滤。
					success: function(res) {
						
						var tempFilePaths = res.tempFilePaths;
						console.log(res)
						console.log(JSON.stringify(tempFilePaths));
						_this.saveRecord(tempFilePaths[0])
					}
				});

			},
			saveRecord(param) {
				uni.showLoading({
					title: '上传中...'
				});
				uni.uploadFile({
					url: 'xxxx', // 上传地址
					filePath: param, // 要上传的文件路径
					name: 'file', // 上传文件对应的 key 值
					formData: {
						"file": param,   //接口需要的参数
						"type": 'recording'
					},
					header: {
						'Authorization': "Bearer " + JSON.parse(uni.getStorageSync('USERS_KEY')).access_token,
					},
					success: function(uploadRes) {
						// 上传成功处理逻辑
						console.log(uploadRes);
						uni.hideLoading();
						uni.showToast({
							title: '上传成功'
						});
					},
					fail: function(error) {
						// 上传失败处理逻辑
						console.log(error);
						uni.hideLoading();
						uni.showToast({
							title: '上传失败'
						});
					}
				});
			},

2.播放

<view  v-for="(recordList,recordIndex) in list":key="'record'+recordIndex" @click="changeState(recordList,recordIndex)">
	<view>
			<view >{{recordList.name}}</view>						
	</view>
</view>

<view class="playRadioClass">
	<view class="audio-play" @click="changeRecordPic">
			<image class="image" :src='recordUrl'></image>
	</view>

	<view class="audio-slider">

		<!-- min进度从0开始    sliderMax进度最大值   sliderChangeComplate快进快退事件   sliderValue播放进度 -->
		<slider class="slider" min="0" :max="sliderMax" @change="sliderChangeComplate"
											block-size="14" :value="sliderValue" activeColor="blue"></slider>
				<view class="audio-time" style="float: left;">
						<text>{{currentTimeStr}}</text>
				</view>
				<view class="audio-time" style="float: right;">
						<text>{{timeStr}}</text>
				</view>
		</view>
</view>
export default {
		computed: {},
		data() {
			return {
				currentTimeStr: '00:00',
				sliderMax: undefined,
				sliderValue: '',
				timeStr: '',
				audioPlay: false,
				recordUrl: '@/../../../static/img/common/play.png',
				innerAudioContext: '',
				csdFileindex: '',
				recordPath: '',
				'list': [{
						'url': `https://bjetxgzv.cdn.bspapp.com/VKCEYUGU-hello-uniapp/2cc220e0-c27a-11ea-9dfb-6da8e309e0d8.mp3`
						
							},
							{
								'url': 'xxxx&download=Y',
							}
						]
			}
		},
		watch: {
			'audioPlay': {
				handler(newVal, oldVal) {

					if (this.audioPlay == true) {
						this.recordUrl = '@/../../../static/img/common/play.png'
					} else {
						this.recordUrl = '@/../../../static/img/common/stop.png'
					}
				},
				deep: true,
				// immediate: true
			},
		},
		methods: {
			//录音实例
			creatAudio() {
				this.innerAudioContext = uni.createInnerAudioContext(); //创建实例
				this.innerAudioContext.src = this.recordPath; //音频的url
				this.innerAudioContext.onPlay(() => {
					// 播放监听
					// console.log('播放!');
					this.audioPlay = true;
				});
				this.innerAudioContext.onPause(() => {
					// 暂停监听
					// console.log('暂停播放!');
					this.audioPlay = false

				});
				this.innerAudioContext.onEnded(() => {
					// 结束播放监听
					// console.log('播放结束!');
					this.audioPlay = false;
					//自动切换事件
					// this.qeihuanwenjian()
				});
				this.innerAudioContext.onTimeUpdate(() => {
					const {
						currentTime,
						duration
					} = this.innerAudioContext; //这俩参数是这个api自带的参数

					const currTimeStr = this.formatTime(currentTime);
					this.sliderValue = parseInt(currentTime);

					// 变动的时间
					this.currentTimeStr = currTimeStr;
					console.log("持续", duration)

					//进度条最大值
					this.sliderMax = duration;
					this.timeStr = Math.round(duration) + 's';
					// this.sliderMax = 0;
				});


			},

			changeRecordPic(item) {
				// 			let self = this
				if (this.audioPlay == false) {
					this.innerAudioContext.play();
				} else {
					this.innerAudioContext.pause()
				}
			},

			// 文件切换播放
			changeState(item, i) {
				if (this.innerAudioContext) {
					this.innerAudioContext.destroy();
				}
				this.csdFileindex = i;
				this.recordPath = item.url;
				this.creatAudio()

				// console.log(this.innerAudioContext)
				// this.sliderMax = xxx;
				// this.timeStr = xxxx;
				this.innerAudioContext.play();
			},
			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;
			},
			formatSecond(seconds) {
				var h = Math.floor(seconds / 3600) < 10 ? '0' + Math.floor(seconds / 3600) : Math.floor(seconds / 3600);
				var m = Math.floor((seconds / 60 % 60)) < 10 ? '0' + Math.floor((seconds / 60 % 60)) : Math.floor((
					seconds / 60 % 60));
				var s = Math.floor((seconds % 60)) < 10 ? '0' + Math.floor((seconds % 60)) : Math.floor((seconds % 60));
				return h + ":" + m + ":" + s;
			},

			//音频前进回退
			sliderChangeComplate(e) {
				const currTimeStr = this.formatTime(e.detail.value)
				this.currentTimeStr = currTimeStr
				this.innerAudioContext.seek(e.detail.value);
				this.innerAudioContext.play();
			},


		},
	}
</script>

<style lang="scss" scoped>
	

	.playRadioClass {
		display: flex;
		flex-direction: row;
		align-items: center;

		.audio-play {
			image {
				width: 100rpx;
				height: 100rpx;
			}

		}

		.audio-slider {
			width: calc(100% - 100rpx);
		}
	}

</style>

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值