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
        });
相关推荐
潜创微科技--高清音视频芯片方案开发8 小时前
2026年对拷线芯片实用对比分析:从需求到选型的全维度指南
音视频·硬件工程
愚公搬代码9 小时前
【愚公系列】《剪映+DeepSeek+即梦:短视频制作》033-调色:废片秒变氛围感大片(HSL的精准调节)
音视频
不才小强17 小时前
macOS 屏幕录制开发完全指南:ScreenCaptureKit与音频采集实战
macos·音视频
大叔_爱编程18 小时前
基于用户评论的热点问题挖掘与反馈分析系统-django+spider+uniapp
python·django·uni-app·毕业设计·源码·课程设计·spider
轻口味1 天前
HarmonyOS 6 NDK开发系列1:音视频播放能力介绍
华为·音视频·harmonyos
大模型实验室Lab4AI1 天前
Demystifing Video Reasoning 论文简析
音视频
天上路人1 天前
A-59F 多功能语音处理模组在本地会议系统扩音啸叫处理中的技术应用与性能分析
人工智能·神经网络·算法·硬件架构·音视频·语音识别·实时音视频
kingcjh971 天前
一、大模型视频生成实战:Wan2.1 本地部署全记录
深度学习·生成对抗网络·ai作画·音视频
枳实-叶1 天前
50 道嵌入式音视频面试题
面试·职场和发展·音视频
源码潇潇和逸逸1 天前
独立部署高校圈子平台:PHP+UniApp打造社交+交易+服务一站式校园解决方案
开发语言·uni-app·php