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
        });
相关推荐
集成显卡13 小时前
前端视频播放方案选型:主流 Web 播放器对比 + Vue3 实战
前端·vue·音视频
爱吃番茄鼠骗14 小时前
回顾ESP32S3系列---音频开发
音视频
ViiTor_AI14 小时前
AI 在线字幕去除工具:一键无损删除视频硬字幕与软字幕
人工智能·音视频
愚公搬代码14 小时前
【愚公系列】《AI短视频创作一本通》027-AI 短视频创作的注意事项及未来展望(AI短视频的技术展望)
人工智能·音视频
binderIPC14 小时前
macos环境下FFmpeg打包成.so文件
macos·ffmpeg·音视频
binderIPC14 小时前
macos的FFmpeg环境搭建
macos·ffmpeg·音视频
ViiTor_AI15 小时前
视频字幕怎么去除?5 种方法删除硬编码字幕与软字幕(CapCut 实操)
人工智能·计算机视觉·音视频
予你@。15 小时前
uni-app(Vue3)实现自定义 Tab 切换滑块效果(微信小程序)
vue.js·微信小程序·uni-app
西***634716 小时前
深耕政务数字化,矩阵会议系统多点落地,解锁政务会商新范式
矩阵·音视频·会议系统
奔跑吧 android17 小时前
【车载audio】【audio hal 01】【Android 音频子系统:Audio HAL Server 启动全流程深度解析】
android·音视频·audio·audioflinger·aosp15·车载音频·audiohal