audio-mixin.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /**
  2. * 音频播放 mixin
  3. * 负责:白噪音初始化、播放/暂停、切换音源
  4. */
  5. let innerAudioContext = null
  6. export default {
  7. data() {
  8. return {
  9. audiolist: [
  10. { name: '河流', posterimg: '/static/device/heliu.png', url: '/static/audio/audio1.mp3' },
  11. { name: '下雨', posterimg: '/static/device/heliu.png', url: '/static/audio/audio2.mp3' }
  12. ],
  13. curAudioInx: 0,
  14. totalTime: 0,
  15. currentTime: 0,
  16. ispause: true,
  17. isShowDrawer3: false
  18. }
  19. },
  20. methods: {
  21. initAudio() {
  22. innerAudioContext = uni.createInnerAudioContext()
  23. innerAudioContext.src = '/static/audio/audio1.mp3'
  24. innerAudioContext.loop = true
  25. innerAudioContext.onPlay(() => {
  26. this.totalTime = innerAudioContext.duration
  27. })
  28. innerAudioContext.onCanplay(() => {
  29. this.totalTime = innerAudioContext.duration
  30. })
  31. innerAudioContext.onError((res) => {
  32. console.log('播放错误', res.errMsg)
  33. })
  34. innerAudioContext.onTimeUpdate(() => {
  35. this.currentTime = innerAudioContext.currentTime
  36. })
  37. },
  38. formatTime(totalSeconds) {
  39. totalSeconds = Math.floor(totalSeconds)
  40. const minutes = Math.floor(totalSeconds / 60)
  41. const seconds = totalSeconds % 60
  42. return minutes.toString().padStart(2, '0') + ':' + seconds.toString().padStart(2, '0')
  43. },
  44. changeAudio(url, inx) {
  45. this.curAudioInx = inx
  46. if (innerAudioContext) {
  47. innerAudioContext.stop()
  48. setTimeout(() => {
  49. innerAudioContext.src = url
  50. this.ispause = true
  51. this.playAudio()
  52. }, 500)
  53. }
  54. },
  55. playAudio() {
  56. if (!innerAudioContext) return
  57. if (this.ispause) {
  58. innerAudioContext.play()
  59. } else {
  60. innerAudioContext.pause()
  61. }
  62. this.ispause = !this.ispause
  63. },
  64. /** 供 ble-mixin 模式切换时调用 */
  65. _stopAudioOnModeChange() {
  66. if (innerAudioContext) {
  67. innerAudioContext.stop()
  68. }
  69. },
  70. destroyAudio() {
  71. if (innerAudioContext) {
  72. innerAudioContext.stop()
  73. innerAudioContext.destroy()
  74. innerAudioContext = null
  75. }
  76. }
  77. }
  78. }