项目需求需要在页面上添加音频播发功能,在官网上<audio >停止维护了,所以使用了uni.getBackgroundAudioManager()

在后台还能继续播放的api接口。

写死的播放路径的代码(代码主体,之后都是在该代码上修改):

    var that=this
	console.log(this.detail.audio,"放入的音频路径")
	this.bgAudioMannager = uni.getBackgroundAudioManager();
	this.bgAudioMannager.singer = '暂无';
	that.bgAudioMannager.title = '我的标题';
	that.bgAudioMannager.src = 'https://img-cdn-qiniu.dcloud.net.cn/uniapp/audio/music.mp3';
	this.bgAudioMannager.coverImgUrl = this.imglist[0];
				
	            this.bgAudioMannager.onPlay(() => {
					console.log('开始播放');
				});
				this.bgAudioMannager.onStop(() => {
					console.log('停止播放');
				});
				
				this.bgAudioMannager.onPause(() => {
					console.log('暂停播放');
				});	
				this.bgAudioMannager.onEnded(() => {
					//初始化 需要的参数
					console.log('自然播放结束事件');
				});
				this.bgAudioMannager.onError((res) => {
					console.log(res.errMsg);
					console.log(res.errCode);
				});
				this.bgAudioMannager.pause()

从官网加加减减的复制进来,十分完美。但是在接活的数据后问题来了!

this.bgAudioMannager.pause(),暂停播发无效了!无论的放在onReady,onLoad,onShow,还是自己的方法上面都是无效的。已经入页面接口返回数据后就自动播放。

仔细看官网后发现了一个小Tip

不管是在哪里注册的这个api只要数据中的音频路径重新赋值后,就会直接播放!!!

所以在原基础上把

that.bgAudioMannager.title = '我的标题';
that.bgAudioMannager.src = 'https://img-cdn-qiniu.dcloud.net.cn/uniapp/audio/music.mp3';

单独拿出来,放在你的音频播放的按钮上面,只有在点击的时候才赋值就好了如下:

(that.bgAudioMannager.title 如果不填的话页面上会报错哦,这个好像的必填项)

    var that = this
	console.log("123", this.bgAudioMannager, this.bgAudioMannager.src)
	if(!this.isPlay){//false
	    console.log("第一次")
		that.bgAudioMannager.title = that.detail.title;
		that.bgAudioMannager.src = that.detail.audio;//当设置了新的 src 时,会自动开始播放
		that.isPlay=true
	}
	console.log("其余")
	this.bgAudioMannager.play()
	timeSet = setInterval(function() {
		that.outTimes();
	}, 1000)

关于音频的进度条就简单了,<setInterval>就可以解决,如下:

outTimes() {
	// 当前进度除以总时长
	console.log(parseInt(this.bgAudioMannager.duration), "总的长度")
	console.log(parseInt(this.bgAudioMannager.currentTime), "当前的长度")
	let allduration=this.bgAudioMannager.duration
	let currentTime=this.bgAudioMannager.currentTime
	this.newTime=parseInt(parseInt(currentTime)/parseInt(allduration)*100)
	if(this.newTime>=100){
	    this.bgAudioMannager.startTime=0
        clearInterval(timeSet); //停止调用
	}
    console.log(this.newTime,"进度条")
},

可以每秒调用这个方法获取音频的进度,赋值在就好了

<progress :percent="newTime" :show-info="false" stroke-width="3" activeColor="#70AC9C" />

tip:一定要注意一个问题,getBackgroundAudioManager 在离开页面后是不会关闭的,如果有需求的话要在onUnload()上面注销一下。

onUnload(){
			console.log("12312onUnload")
			clearInterval(timeSet); //停止调用
			this.bgAudioMannager.stop()
			this.newTime=0;
			this.playStop=true;
			this.isPlay=false,
			this.bgAudioMannager.src ='';//当设置了新的 src 时,会自动开始播放
		},
  • 小程序平台,需在manifest.json 对应的小程序节点下,填写"requiredBackgroundModes": ["audio"]。发布小程序时平台会审核

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐