index.vue 2.7 KB
<template>
	<view class="VoicePlayback" @click="operation">
		<view class="VoicePlayback-1">
			<image class="VoicePlayback-1-i" v-if="isPlay" src="@/static/imagesV2/icon42s.png" mode="widthFix"></image>
			<image class="VoicePlayback-1-i" v-else src="@/static/imagesV2/icon42.png" mode="widthFix"></image>
		</view>
		<view class="VoicePlayback-2">{{ convertTimeToHMS(remainingTime) }}</view>
	</view>
</template>

<script>
	export default {
		name: 'VoicePlayback',
		data() {
			return {
				audioContext: null,
				duration: 0, // 音频的总时长(单位:秒)
				currentTime: 0, // 音频的当前播放时间(单位:秒)
				remainingTime: 0,// 音频的剩余播放时间(单位:秒)
				totalDuration: 0,
				isPlay: false
			}
		},
		mounted() {
			this.init()
		},
		onUnload() {
			this.audioContext.stop();
			this.audioContext.destroy();
		},
		methods: {
			operation() {
				if(!this.isPlay) {
					this.audioContext.play()
				} else {
					this.audioContext.pause()
				}
			},
			setUrl(url) {
				this.audioContext.src  = url
			},
			init() {
				this.audioContext = wx.createInnerAudioContext();
				this.audioContext.src = require("@/static/imagesV2/test.mp3")
				this.audioContext.onPlay(() => {
					this.isPlay = true
				});
				this.audioContext.onPause(() => {
					this.isPlay = false
				});
				this.audioContext.onEnded(() => {
					this.audioContext.stop()
				})
				this.audioContext.onStop(() => {
					this.isPlay = false
				});
				this.audioContext.onCanplay(() => {
					this.audioContext.play()
					this.audioContext.pause()
					setTimeout(() => {
						this.duration = this.audioContext.duration
						this.remainingTime = this.duration
					}, 100)
				})
				this.audioContext.onTimeUpdate(() => {
					this.duration = this.audioContext.duration
					this.currentTime = this.audioContext.currentTime
					this.remainingTime = this.duration - this.currentTime
				});
			},
			convertTimeToHMS(time) {
				console.log(time)
				time = parseInt(time)
				var hours = Math.floor(time / 3600);
				  var minutes = Math.floor((time % 3600) / 60);
				  var seconds = time % 60;
				
				  var hhmmss = "";
				  if (hours < 10) {
					hhmmss += "0";
				  }
				  hhmmss += hours + ":";
				
				  if (minutes < 10) {
					hhmmss += "0";
				  }
				  hhmmss += minutes + ":";
				
				  if (seconds < 10) {
					hhmmss += "0";
				  }
				  hhmmss += seconds;
				
				  return hhmmss;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.VoicePlayback{
		padding: 16rpx 18rpx;
		background-color: #fff;
		border-radius: 20rpx;
		display: flex;
		align-items: center;
		.VoicePlayback-1{
			.VoicePlayback-1-i{
				height: 42rpx;
				width: 42rpx;
			}
		}
		.VoicePlayback-2{
			font-size: 26rpx;
			margin-left: 18rpx;
		}
	}
</style>