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
        });
相关推荐
EasyGBS1 小时前
EasyGBS算法算力融合架构:GB28181标准平安乡村智能视频监控建设方案设计
架构·音视频
科技小E2 小时前
EasyGBS算法算力融合架构:标准平安乡村智能视频监控建设方案设计
架构·音视频
雾江流3 小时前
小喵播放器 1.1.5| 视频超分提升画质,支持网页视频,B站番剧
音视频·软件工程
li星野4 小时前
OpenCV4.X学习-视频相关
学习·音视频
雪风飞舞5 小时前
python根据音频生成柱状图
开发语言·python·音视频
狗狗学不会5 小时前
RK3588 极致性能:使用 Pybind11 封装 MPP 实现 Python 端 8 路视频硬件解码
人工智能·python·音视频
2501_915918415 小时前
除了 Perfdog,如何在 Windows 环境中完成 iOS App 的性能测试工作
android·ios·小程序·https·uni-app·iphone·webview
知南x6 小时前
【物联网视频监控系统----韦东山老师视频总结】(4)流媒体方案的实现之ffmpeg
ffmpeg·音视频
丢,捞仔6 小时前
uni-app上架应用添加权限提示框
前端·javascript·uni-app
老兵发新帖6 小时前
基于Label Studio的视频标注与YOLO模型训练全流程指南
python·yolo·音视频