// 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: '00:00', isPlay: false, audioExample: null, progress: 0, allAudio: [], G_AUDIO, timer:null, 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].audio; this.data.audioExample.play(); app.globalData.AllExample.forEach((simpleAudio) => { if (simpleAudio.src && simpleAudio.src!=this.data.audioExample.src) { simpleAudio.src && simpleAudio.pause(); } }) this.setData({ isPlay: true }) this.loadProgress() } else{ this.data.audioExample.pause(); 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) if (progress === 100 || isNaN(this.data.progress)) { clearInterval(this.data.timer) console.log('停止了') this.setData({ isPlay: false, progress: 0, currentTime: "00:00", }) } 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 }) // this.data.audioExample = wx.createInnerAudioContext(); //所有组件实例都放在一个容器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(()=> { console.log('onPause。。。') this.setData({ isPlay: false }) }) // 每个组件实例播放结束 this.data.audioExample.onEnded(() => { this.setData({ currentTime: "00:00", isPlay: false, progress: 0, }) clearInterval(this.data.timer) }) // 在组件实例进入页面节点树时执行 }, detached: function () { // 在组件实例被从页面节点树移除时执行 // 卸载 this.data.audioExample.destroy(); this.setData({ currentTime: "00:00", isPlay: false, progress: 0, }) } })