微信小程序播放音频


官方案例:








Page({
  onReady: function (e) {
    // 使用 wx.createAudioContext 获取 audio 上下文 context
    this.audioCtx = wx.createAudioContext('myAudio')
  },
  data: {
    poster: 'http://y.gtimg.cn/music/photo_new/T002R300x300M000003rsKF44GyaSk.jpg?max_age=2592000',
    name: '此时此刻',
    author: '许巍',
    src: 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E06DCBDC9AB7C49FD713D632D313AC4858BACB8DDD29067D3C601481D36E62053BF8DFEAF74C0A5CCFADD6471160CAF3E6A&fromtag=46',
  },
  audioPlay: function () {
    this.audioCtx.play()
  },
  audioPause: function () {
    this.audioCtx.pause()
  },
  audio14: function () {
    this.audioCtx.seek(14)
  },
  audioStart: function () {
    this.audioCtx.seek(0)
  }
})

实现效果图:

使用这个官方的案例会有一些错误提示:

[/__pageframe__/index/index]  '
[渲染层网络层错误] Failed to load media http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E06DCBDC9AB7C49FD713D632D313AC4858BACB8DDD29067D3C601481D36E62053BF8DFEAF74C0A5CCFADD6471160CAF3E6A&fromtag=46
the server responded with a status of 403 (HTTP/1.1 403 Forbidden) 
From server 117.169.113.108

这个属于警告,提示使用wx.createInneraudioContext

使用Demo:

效果图

wxml:



  

js:

// 创建一个音频组件
const myAudio = wx.createInnerAudioContext()
Page({
  data: {
    isPlay: false,
    audioSrc: '播放的音频链接'
  },

  playAudio(){
    let isPlay = this.data.isPlay
    // console.log(isPlay)
    // 如果当前没有播放音频,则点击之后开始播放音频
    if(!isPlay){
      myAudio.src=this.data.audioSrc
      myAudio.play()
    }else{
      myAudio.pause();
    }
    this.setData({
      isPlay: !isPlay
    })
  },
})

wxss

.playBtn{
  z-index: 3;
  position: absolute;
  width: 200rpx;
  height: 200rpx;
  background-color: #ffffff;
  transform: translate(-50%, -50%);
  border-radius: 125rpx;
  box-shadow: 0 40rpx 60rpx 20rpx rgba(0, 0, 0, 0.1);
}

.playBtn image{
  width: 100%;
  height: 100%;
}

.play {
  left: calc(50% - 100rpx);
  top: calc(50% - 100rpx);
  animation: rotate 10s linear infinite;
}

.pause{
  left: calc(50%);
  top: calc(50%);
}

@keyframes rotate {
  from {
      transform: rotate(0deg)
  }
  to {
      transform: rotate(360deg)
  }
}