background-audio.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. const app = getApp()
  2. const util = require('../../../../util/util.js')
  3. const dataUrl = 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E061FF02C31F716658E5C81F5594D561F2E88B854E81CAAB7806D5E4F103E55D33C16F3FAC506D1AB172DE8600B37E43FAD&fromtag=46'
  4. Page({
  5. onShareAppMessage() {
  6. return {
  7. title: '背景音乐',
  8. path: 'page/API/pages/background-audio/background-audio'
  9. }
  10. },
  11. onLoad() {
  12. this._enableInterval()
  13. if (app.globalData.backgroundAudioPlaying) {
  14. this.setData({
  15. playing: true
  16. })
  17. }
  18. },
  19. data: {
  20. playing: false,
  21. playTime: 0,
  22. formatedPlayTime: '00:00:00'
  23. },
  24. play() {
  25. const that = this
  26. wx.playBackgroundAudio({
  27. dataUrl,
  28. title: '此时此刻',
  29. coverImgUrl: 'http://y.gtimg.cn/music/photo_new/T002R300x300M000003rsKF44GyaSk.jpg?max_age=2592000',
  30. complete() {
  31. that.setData({
  32. playing: true
  33. })
  34. }
  35. })
  36. this._enableInterval()
  37. app.globalData.backgroundAudioPlaying = true
  38. },
  39. seek(e) {
  40. clearInterval(this.updateInterval)
  41. const that = this
  42. wx.seekBackgroundAudio({
  43. position: e.detail.value,
  44. complete() {
  45. // 实际会延迟两秒左右才跳过去
  46. setTimeout(function () {
  47. that._enableInterval()
  48. }, 2000)
  49. }
  50. })
  51. },
  52. pause() {
  53. const that = this
  54. wx.pauseBackgroundAudio({
  55. dataUrl,
  56. success() {
  57. that.setData({
  58. playing: false
  59. })
  60. }
  61. })
  62. app.globalData.backgroundAudioPlaying = false
  63. },
  64. stop() {
  65. const that = this
  66. wx.stopBackgroundAudio({
  67. dataUrl,
  68. success() {
  69. that.setData({
  70. playing: false,
  71. playTime: 0,
  72. formatedPlayTime: util.formatTime(0)
  73. })
  74. }
  75. })
  76. app.globalData.backgroundAudioPlaying = false
  77. },
  78. _enableInterval() {
  79. const that = this
  80. function update() {
  81. wx.getBackgroundAudioPlayerState({
  82. success(res) {
  83. that.setData({
  84. playTime: res.currentPosition,
  85. formatedPlayTime: util.formatTime(res.currentPosition + 1)
  86. })
  87. }
  88. })
  89. }
  90. update()
  91. this.updateInterval = setInterval(update, 500)
  92. },
  93. onUnload() {
  94. clearInterval(this.updateInterval)
  95. }
  96. })