WeChat applet simple audio player (wx.getBackgroundAudioManager())

Development tools: WeChat developer tools

Source code (Baidu Netdisk:) link ; extraction code: ldb9

Note: If there is no response when clicking play, or if it becomes popular, you need to change the video address in js.


The first step is to set it in app.json:

"requiredBackgroundModes":["audio","backgroundAudioManager"]

 Step 2: Set up js and wxml

(1) Configure js

// index.js
// 获取应用实例
const app = getApp()

// 接口返回数据中拿到的歌曲数据
const backgroundAudioManager = wx.getBackgroundAudioManager();

Page({
  data: {
  },
  startMusic() {
    // 音乐播放
    backgroundAudioManager.title = '歌曲标题'; //
    // 设置了 src 之后会自动播放
    backgroundAudioManager.src = 'https://sd-sycdn.kuwo.cn/bdebe3992dc2d21d5a4bd2f8340d8b9c/635bf887/resource/n2/46/38/3150269113.mp3';
  },

  //播放
  onMusic() {
    backgroundAudioManager.play();
    backgroundAudioManager.onPlay(() => {
      console.log('开始播放');
    })
    this.setData({
      onplay: false
    })
  },
  //暂停
  pauseMusic() {
    backgroundAudioManager.pause();
    backgroundAudioManager.onPause(() => {
      console.log('暂停播放');
    })
    this.setData({
      onplay: true
    })
  },
  //停止
  stopMusic() {
    backgroundAudioManager.stop();
    backgroundAudioManager.onStop(() => {
      console.log('停止播放');
    })
    this.setData({
      onplay: true
    })
  },

  onLoad() {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
  },
})

 (2) Configure wxml

<!--index.wxml-->
<view class="container">
  <button bindtap="startMusic">播放音乐</button>
  <button bindtap="pauseMusic">暂停</button>
  <button bindtap="onMusic">继续播放</button>
  <button bindtap="stopMusic">停止</button>
</view>

3. Effect display (only picture display provided)

Guess you like

Origin blog.csdn.net/caip12999203000/article/details/127581476