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
        });
相关推荐
音视频牛哥9 小时前
Android音视频开发:基于 Camera2 API 实现RTMP推流、RTSP服务与录像一体化方案
android·音视频·安卓camera2推流·安卓camera2推送rtmp·安卓camera2 rtsp·安卓camera2录制mp4·安卓实现ipc摄像头
summerkissyou198713 小时前
android13-audio-AudioTrack-写数据流程
android·音视频
卢卡上学14 小时前
【AI工具】Coze智能体工作流:5分钟制作10个10w+治愈视频,无需拍摄剪辑
人工智能·音视频·ai视频·ai智能体
zimoyin15 小时前
WSL音频转发配置流程:WSL2/WSL1全适配
linux·音视频·wsl·虚拟机·ekho
优选资源分享17 小时前
foobar2000 2.25.3 汉化版:Windows 音频播放器
音视频
mcu201821 小时前
3.5mm音频口对外输出的音量和电压测试
音视频
阿伟*rui1 天前
互联网大厂Java面试:音视频场景技术攻防与系统设计深度解析
java·redis·websocket·面试·音视频·高并发·后端架构
Android系统攻城狮1 天前
Android16音频之获取Track状态AudioTrack.getState:用法实例(一百二十九)
音视频·android16·音频进阶·track状态
kkk_皮蛋1 天前
RTP 协议详解:WebRTC 音视频传输的基石
音视频·webrtc
音视频牛哥1 天前
深度解析SmartPlayer:如何打造工业级Android RTSP/RTMP直播播放器
音视频·rtsp播放器·rtmp播放器·安卓超低延迟rtsp播放器·安卓超低延迟rtmp播放器·rtsp播放器安卓端·rtmp播放器安卓端