Last active
April 27, 2020 04:08
-
-
Save jschee/37b1714c1cfb5388ab4cb2d3f7d763a4 to your computer and use it in GitHub Desktop.
wx audio playback boilerplate.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Data variables | |
responses: [ | |
{ | |
id: '', | |
playUrl: '', | |
duration: 100, | |
likes: 0, | |
avatar: '', | |
username: '', | |
title: '' | |
} | |
], | |
playUrl: '', | |
duration: '', | |
first: '', | |
audio_playing: false | |
// Play audio first time | |
playAudio: function (e) { | |
let responses = this.data.responses; | |
let playurl = e.currentTarget.dataset.playurl; | |
let duration = e.currentTarget.dataset.duration; | |
let title = e.currentTarget.dataset.title; | |
for (let i of responses) { | |
this.setData({ | |
duration: this.formatTime(duration), | |
playurl: playurl, | |
first: true, | |
title: title | |
}) | |
} | |
this.createAudio(playurl, duration, title) | |
}, | |
// Create audio instance | |
createAudio: function (playurl, duration, title) { | |
// initialize audio | |
wx.playBackgroundAudio({ | |
dataUrl: playurl, | |
title: title | |
}) | |
// play audio | |
wx.onBackgroundAudioPlay(() => { | |
this.setData({ | |
audio_playing: true, | |
}) | |
}) | |
// pause audio | |
wx.onBackgroundAudioPause(() => { | |
this.setData({ | |
audio_playing: false, | |
}) | |
}) | |
// audiomanager update playback time | |
const manage = wx.getBackgroundAudioManager() | |
manage.onTimeUpdate(() => { | |
const currentTime = manage.currentTime | |
this.setData({ | |
currentTime: this.formatTime(currentTime), | |
percent: currentTime / duration * 100 | |
}) | |
}) | |
}, | |
// Log duration and timing functions | |
formatTime: function (interval) { | |
interval = interval | 0 | |
const minutes = interval / 60 | 0 | |
const seconds = this.calcSeconds(interval % 60) | |
return `${minutes}:${seconds}` | |
}, | |
calcSeconds(num, n = 2) { | |
let len = num.toString().length | |
while (len < n) { | |
num = '0' + num | |
len++ | |
} | |
return num | |
}, | |
// Toggle Audio Playing | |
togglePlaying: function (e) { | |
wx.getBackgroundAudioPlayerState({ | |
success: function (res) { | |
var status = res.status | |
console.log('bg music: ', status) | |
if (status == 1) { | |
wx.pauseBackgroundAudio() | |
} else { | |
wx.playBackgroundAudio() | |
} | |
} | |
}) | |
}, | |
// In app.json make sure to add | |
"requiredBackgroundModes": [ | |
"audio" | |
], |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment