// components/audio-play.js import { CDN_URL,API_BASE_URL,G_AUDIO } from '../../config/index'; let app = getApp(); Component({ /** * 组件的属性列表 */ properties: { audio: { type: Number } }, /** * 组件的初始数据 */ data: { cdn_url:CDN_URL, currentTime: '', isPlay: false, audioExample: null, G_AUDIO, timer:null, progress: 0, allAudio: [], api_base_url:API_BASE_URL, targetUrl:API_BASE_URL+'/data/' }, /** * 组件的方法列表 */ methods: { toggleMusic() { // 全部暂停 if (!this.data.isPlay) { this.data.audioExample.autoplay = true; this.data.audioExample.src = G_AUDIO[this.properties.audio] && (G_AUDIO[this.properties.audio].audio +`?${Math.random()}`); this.data.audioExample.play(); this.setData({ isPlay: true }) app.globalData.AllExample.forEach((simpleAudio) => { if (simpleAudio.src && simpleAudio.src!=this.data.audioExample.src) { simpleAudio.src && simpleAudio.pause(); } }) this.loadProgress() } else{ this.data.audioExample.pause(); console.log('结束音乐') this.setData({ isPlay: false }) } }, // 播放中 loadProgress() { this.data.audioExample.onCanplay(() => { this.data.timer = setInterval(() => { // 只要音频暂停了,定时器(假的)不执行 if (this.data.audioExample.paused) return; var currentime = this.data.audioExample.currentTime; var currTimeStr = this.formatTime(currentime); var progress = parseInt((this.data.audioExample.currentTime / this.data.audioExample.duration) * 100) console.log(this.data.audioExample.currentTime, this.data.audioExample.duration,'111111'); if (progress === 100 || isNaN(this.data.progress)) { clearInterval(this.data.timer) this.setData({ isPlay: false, progress: 0, currentTime: "", }) } else { this.setData({ progress, currentTime: currTimeStr }) } }, 1000); }); }, formatTime: function (num) { //格式化时间格式 num = num.toFixed(0); let second = (num % 60); if (second < 10) second = '0' + second; let min = Math.floor(num / 60); if (min < 10) min = '0' + min; return min + ":" + second; } }, attached: function () { //组件显示初始化函数 let tt = wx.createInnerAudioContext() tt.src = 'none' this.setData({ audioExample: tt }) //所有组件实例都放在一个容器AllExample里 app.globalData.AllExample.push(this.data.audioExample); this.data.audioExample.onPlay(function () { console.log('播放中。。。') }) this.data.audioExample.onTimeUpdate(function () { console.log('监听进度。。') }) //控制单个实例的isPlay this.data.audioExample.onPause( ()=> { this.setData({ isPlay: false }) }) // 每个组件实例播放结束 this.data.audioExample.onEnded(() => { this.setData({ currentTime: "", isPlay: false, progress: 0, }) clearInterval(this.data.timer) }) // 在组件实例进入页面节点树时执行 }, detached: function () { // 在组件实例被从页面节点树移除时执行 // 卸载 this.data.audioExample.destroy(); } })