uniapp音频类

功能:

1.可以设置固定地时间间隔播放循环

javascript 复制代码
export default {
	audio: null,
	playInterval: 0, // 播放间隔时间(毫秒)
	time: null,

	init(src, options) {
		let that = this;
		that.playInterval = options.playInterval ?? 5000
		return new Promise((resolve, reject) => {
			try {
				if (that.audio === null) {
					that.audio = uni.createInnerAudioContext();
					that.audio.src = src || 'https://web-ext-storage.dcloud.net.cn/uni-app/ForElise.mp3';

					that.setProperty(options)

					// 可以在这里设置其他属性,如音量等
					console.log('auto+++++++++++++', that.audio)
					// utils.sleep(3000);
					resolve(that.audio)
				} else {
					resolve(that.audio)
				}
			} catch (e) {
				//TODO handle the exception
				reject()
			}
		})
	},

	setProperty(obj) {
		Object.assign(this.audio, obj)
	},
	play() {
		if (this.audio) {
			this.audio.play();
			if (this.playInterval && !this.audio.loop) {
				this.audio.onEnded(this.onEndedHandle())
			}

		}
	},
	onEndedHandle() {
		// 设置定时器,在指定的时间间隔后再次播放
		let that = this;
		that.time = setTimeout(() => {
			that.play()
		}, that.playInterval)
		console.log(that.playInterval, '设置定时器,在指定的时间间隔后再次播放')
	},

	pause() {
		console.log('暂停')
		if (this.audio) {
			this.audio.pause();
			if (this.playInterval && !this.audio.loop) {
				this.clearCustomPlayInterval()
			}
		}
	},

	clearCustomPlayInterval() {
		clearTimeout(this.time)
		console.log(this.time)
		this.audio.offEnded()
	},

	stop() {
		if (this.audio) {
			if (this.playInterval) {
				this.clearCustomPlayInterval()
			}
			this.audio.stop();
			this.audio.destroy(); // 销毁音频上下文
			this.audio = null;
		}
	},

	onPlay(callback) {
		if (this.audio) {
			this.audio.onPlay(callback);
		}
	},

	onPause(callback) {
		if (this.audio) {
			this.audio.onPause(callback);
		}
	},

	onStop(callback) {
		if (this.audio) {
			this.audio.onStop(callback);
		}
	},
	onError(callback) {
		if (this.audio) {
			this.audio.onError(callback)
		}
	}
};

使用

javascript 复制代码
import musicPlayer from '@/common/musicPlayer';
musicPlayer.init('/static/mp4.mp3', {
            obeyMuteSwitch: false,
            loop: false,
            playInterval: 12000
        });
相关推荐
apollo_qwe20 小时前
解决移动端键盘遮挡痛点
uni-app
沃达德软件21 小时前
视频侦查技术揭秘
人工智能·opencv·计算机视觉·视觉检测·音视频·实时音视频·视频编解码
忧云1 天前
解锁视频动感密码:AE Twitch 插件全方位使用指南
音视频
沃达德软件1 天前
视频标注技术全解析
人工智能·目标检测·计算机视觉·视觉检测·音视频·实时音视频·视频编解码
却道天凉_好个秋1 天前
音视频学习(八十):离散余弦变换(DCT)
音视频·dct·视频压缩
源代码杀手1 天前
Fun-Audio-Chat-8B 大型音频语言模型(Large Audio Language Model)
人工智能·语言模型·音视频
ACP广源盛139246256731 天前
GSV2125D@ACP#2125产品规格参数详解及产品应用分享
嵌入式硬件·计算机外设·音视频
weixin199701080161 天前
TikTokitem_search_video关键词视频列表接口对接全攻略:从入门到精通
java·服务器·音视频
却道天凉_好个秋1 天前
音视频学习(八十一):JPEG编解码
音视频·视频压缩·jpeg编码
我可以将你更新哟1 天前
【爬虫】下载ffmpeg,爬取b站视频,把音频和视频合成一个视频
爬虫·ffmpeg·音视频