Skip to content

Instantly share code, notes, and snippets.

@jschee
Last active April 27, 2020 04:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jschee/37b1714c1cfb5388ab4cb2d3f7d763a4 to your computer and use it in GitHub Desktop.
Save jschee/37b1714c1cfb5388ab4cb2d3f7d763a4 to your computer and use it in GitHub Desktop.
wx audio playback boilerplate.
// 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