inner-audio-mult.uvue 2.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
<template>
	<page-head :title="title"></page-head>
	<view class="uni-padding-wrap uni-common-mt">
		<view class="uni-title">
			<text class="uni-title-text">多音频同时播放</text>
		</view>
		<button type="primary" @tap="play1()"> 播放/停止(进度:{{currentTime1}})</button>
		<button type="primary" @tap="play2()"> 播放/停止(进度:{{currentTime2}})</button>
	</view>
</template>

<script>
	type AudioPath = {
		description : string
		src : string
	}
	export default {
		data() {
			return {
				title: "多音频同时播放",
				_audioContext1: null as InnerAudioContext | null,
				src: 'https://web-ext-storage.dcloud.net.cn/uni-app/ForElise.mp3',
				_audioContext2: null as InnerAudioContext | null,
				playing1: false,
				playing2: false,
				currentTime1: 0,
				currentTime2: 0,
			}
		},
		onReady() {
			this._audioContext1 = uni.createInnerAudioContext();
			this._audioContext1!.src = this.src
			this._audioContext1!.onTimeUpdate((res) => {
				this.currentTime1 = this._audioContext1!.currentTime;
			})
			this._audioContext2 = uni.createInnerAudioContext();
			this._audioContext2!.src = this.src
			this._audioContext2!.onTimeUpdate((res) => {
				this.currentTime2 = this._audioContext2!.currentTime;
			})
		},

		onUnload() {
			if (this._audioContext1 != null) {
				this._audioContext1!.stop()
				this._audioContext1!.destroy()
			}
			if (this._audioContext2 != null) {
				this._audioContext2!.stop()
				this._audioContext2!.destroy()
			}
		},
		methods: {
			play1() {
				if (this._audioContext1 != null) {
					this.currentTime1=0
					if (this.playing1) {
						this._audioContext1!.stop()
					} else {
						this._audioContext1!.play()
					}

				}
				this.playing1 = !this.playing1
			},
			play2() {
				if (this._audioContext2 != null) {
					this.currentTime2=0
					if (this.playing2) {
						this._audioContext2!.stop()
					} else {
						this._audioContext2!.play()
					}

				}
				this.playing2 = !this.playing2
			}
		}
	}
</script>

<style>
	.formats {
		align-items: center;
	}

	.icon-play {
		width: 60px;
		height: 60px;
		margin: 10px;
	}
</style>