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
        });
相关推荐
KOYUELEC光与电子请努力拼搏~8 小时前
ESS艾西斯音频解码芯片ESS9039PRO特点
音视频
音视频牛哥13 小时前
【深度选型】RTSP超低延迟播放器:自研陷阱与成熟模块的效益分析
音视频·rtsp播放器·低延迟rtsp播放器·linux rtsp播放器·windows rtsp播放器·安卓rtsp播放器·ios rtsp播放器
ACP广源盛1392462567316 小时前
GSV2231G@ACP#2231G产品规格详解及产品应用分享
嵌入式硬件·计算机外设·音视频
这儿有一堆花19 小时前
音频也有水印!不可察觉的声波密码
音视频
ACP广源盛1392462567320 小时前
GSV6505F@ACP#6505F产品规格详解及产品应用分享
单片机·嵌入式硬件·计算机外设·音视频
gf132111121 小时前
python_制作视频开头_根据短句字长占总字幕的长度比例拆分
windows·python·音视频
专业开发者1 天前
行业专家解读蓝牙 ® 低功耗音频(LE Audio)
物联网·音视频
LeeZhao@1 天前
【狂飙全模态】狂飙AGI-Wan2.1文生视频实战部署-Gradio篇
人工智能·语言模型·音视频·agi
感谢地心引力1 天前
【AI】加入AI绘图的视频封面快速编辑器
人工智能·python·ai·ffmpeg·音视频·pyqt·gemini
我这一生如履薄冰~1 天前
uni-app 项目配置代理踩坑
uni-app