Uniapp Base64码 播放音频(MP3)

好多人说以下代码播放不了MP3,我从源代码里复制了一份,代码迭代太多了可能更新不及。
以下是最新的代码,在生产环境中已经应用验证了的

我记得没错的话,使用http请求数据的时候播放不出来,所以用了文件流的形式,具体原因也不记得了,有大佬的解释一下的话可以评论,供大家学习,此处抱拳

onRequestVoice(url) {
				let that = this
					console.log('请求语音==URL='+url)
				uni.downloadFile({
					url: url,
					header: {
						'X-Access-Token': that.token
					},
					success: (res) => {
						/* 此处做拦截 界面已经关闭  但是语音还有可能会触发
						 所以写定isshowView标志位
						 */
						if (!that.isshowView) {
							return
						}
						if (res.statusCode == 200) {
							let mp3url = res.tempFilePath
							let mp3data = mp3url
							that.innerAudioContext.src = mp3data;
							that.innerAudioContext.autoplay = true
						
							that.innerAudioContext.onPlay(() => {
								that.isAudoplaying = true;
								console.log('播放开始')
							});
							that.innerAudioContext.onEnded(() => {
								that.onStopAudio()

							})
							that.innerAudioContext.onError((res) => {
								console.log('播放音频失败' + JSON.stringify(res));
								that.onStopAudio()
							})
							that.innerAudioContext.play()
						}
					},
					fail: (err) => {
						that.$u.toast('播放失败')
						console.log('语音流失败=' + JSON.stringify(err))
					},
					complete: () => {
						that.onStopAudio()
						console.log('语音流结束...')
					}
				})
			}

-----------------------以下弃用代码----------------------------

let innerAudioContext = uni.createInnerAudioContext();
					innerAudioContext.autoplay = true;
					innerAudioContext.src = 'data:audio/mp3;base64,'+base64Mp3.replace(/[\r\n]/g, "");
					innerAudioContext.onPlay(() => {
						console.log('开始播放');
					});

其他地方调用

innerAudioContext .play();

更多功能请查阅【官方文档】

评论 23
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值