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
        });
相关推荐
敲代码的鱼哇12 小时前
发送短信/拨打电话/获取联系人能力 UTS 插件(cz-sms)
android·前端·ios·uni-app·安卓·harmonyos·鸿蒙
我是发哥哈13 小时前
主流AI视频生成方案商用化能力横向评测
大数据·人工智能·学习·机器学习·chatgpt·音视频
reasonsummer13 小时前
【教学类-160-10】20260418 AI视频培训-练习011“豆包AI视频《毛毛虫找妈妈》+豆包图片风格:水墨画”
音视频·豆包图片
liulian091615 小时前
【Flutter for OpenHarmony第三方库】Flutter for OpenHarmony 音频播放功能适配与实现指南
flutter·华为·音视频·学习方法·harmonyos
互联科技报16 小时前
2026年短视频矩阵视频混剪软件工具商业分析报告
线性代数·矩阵·音视频
philsonzhao16 小时前
ffmpeg如何剪辑视频,并保留字幕
音视频
byte轻骑兵17 小时前
【LE Audio】BASS精讲[3]: 从服务声明到行为逻辑 解锁广播音频接收核心
音视频·实时音视频·le audio·低功耗音频·蓝牙通话
ai产品老杨17 小时前
深度解析:基于异构计算的工业级AI视频中台架构,如何实现GB28181/RTSP跨平台部署与源码交付?
人工智能·架构·音视频
枫叶丹418 小时前
【HarmonyOS 6.0】AVCodec Kit 视频解码器平滑停用机制详解
开发语言·华为·音视频·harmonyos
ai产品老杨18 小时前
告别重复造轮子:深度解析支持源码交付的 AI 视频平台架构,实现 X86/ARM 与 GPU/NPU 异构算力融合
人工智能·架构·音视频