【uni-app】用uni.createInnerAudioContext代替audio

uni.createInnerAudioContext能够创建并返回内部audio上下文innerAudioContext对象,从而代替audio组件。

为了兼容性和音质,推荐使用mp3格式
在pages文件夹下创建文件,其代码如下:

<template>
	<view>
		<view class="page-body">
			<view class="page-section page-section-gap" style="text-align:center;">
				<button type="default" @click="doPlay()">播放</button>
				<button type="default" @click="doPause()">暂停</button>
				<view style="margin-top: 20rpx;">当前播放时间:{{ currentTime }} / {{ duration }}</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default{
		name: 'audio-component',
		data(){
			return {
				currentTime: "00:00",
				duration:"00:00"
			}
		},
		onLoad(){
			this.timer = null;
			this.innerAudioContext = uni.createInnerAudioContext();
			// 监听音频进入可以播放状态的事件
			this.innerAudioContext.onCanplay(()=>{
				this.innerAudioContext.duration;
				// 延迟大约300ms以上才能获取音频总时长
				setTimeout(()=>{
					// 获取音频总时长
					this.duration = this.formatSeconds(this.innerAudioContext.duration);
				},300)
			})// 监听音频播放
			this.innerAudioContext.onPlay(()=>{
				// 获取当前音频的播放时间
				this.timer = setInterval(()=>{
					this.currentTime = this.formatSeconds(this.innerAudioContext.currentTime);
				},1000)
		
			})
			
		},
		onUnload(){
			clearInterval(this.timer);
			// 销毁innerAudioContext实例
			this.innerAudioContext.destroy();
		},
		methods:{
			// 播放
			doPlay(){
				if (!this.innerAudioContext.src) {
			        // 音频地址
			        this.innerAudioContext.src = "/static/RedVelvet_ZOOM.flac";
		      	}
				this.innerAudioContext.play();
			},
			doPause(){
				this.innerAudioContext.pause();
				// 清除定时器
				clearInterval(this.timer);
			},
			// 将秒转换成03:30格式
			formatSeconds(value){
				let minute = parseInt(value/60);
				let second = parseInt(value%60);
				if(minute<10){
					minute = "0"+minute
				}
				if(second<10){
					second = "0"+second 
				}
				return minute+":"+second;
			}
		}
	}
</script>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值