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
        });
相关推荐
大拿爱科技7 小时前
低清视频修复怎么接入批处理?AI画质增强流程拆解
人工智能·自动化·aigc·音视频
ZC跨境爬虫12 小时前
跟着 MDN 学 HTML day_56:(HTML 表格基础完全指南)
前端·javascript·ui·html·音视频
泰兰尼斯稳稳鞋12 小时前
推荐一款视频无损裁剪的软件:losslesscut
音视频·视频剪辑·视频无损裁剪
EasyDSS14 小时前
企业级融媒体生产管理平台/智能会议管理系统EasyDSS构建一体化应急视频指挥体系
音视频·媒体
大拿爱科技15 小时前
视频里的字幕和文案怎么批量提取?从ASR到内容复用的工具拆解
aigc·音视频·语音识别
ZC跨境爬虫16 小时前
跟着 MDN 学 HTML day_55:HTML 音频与视频嵌入实战指南
前端·javascript·ui·html·音视频·媒体
aqi0017 小时前
FFmpeg开发笔记(一百零二)国产的音视频移动开源工具FFmpegAndroid
android·ffmpeg·kotlin·音视频·直播·流媒体
福大大架构师每日一题17 小时前
ComfyUI v0.21.0 更新解读:视频音频同步加载、PyAV 图像引擎切换、动态显存优化、云端与工作流能力全面升级
音视频·comfyui
ZC跨境爬虫18 小时前
跟着 MDN 学 HTML day_57:(HTML 表格进阶特性与无障碍实践)
java·前端·javascript·ui·html·音视频
网管NO.118 小时前
视频核心技术 01:视频基础概念 —— 帧、分辨率、帧率、码率、YUV 色彩系统全解
音视频