微信小程序中如何应用音频

前几天在小程序中使用音频时发现一个问题:音频只能在模拟器中播放,
在这里写下两种解决的方法:

1、解决微信小程序 audio 组件在 ios 端无法播放问题

audio组件自带的播放暂停功能只在模拟器中生效

实现原理:

audio 组件绑定点击事件,手动触发播放暂停方法!


<audio 
	id="myAudio" 
	src="{{src}}" 
	poster="{{shortImg}}"
	bindtap='audioClick' 
	bindended="playEnd"  
	name="标题" 
	author="歌手"
  	controls>
</audio>
  data: {
    
    isPlaying: false, // 是否播放
  	shortImg:'https://tiebapic.baidu.com/forum/w%3D580/sign=80f40f96e71f3a295ac8d5c6a924bce3/1cd9720e0cf3d7ca776b913ee51fbe096963a9d0.jpg',
    src:'https://magic-mirror-oss.oss-cn-shanghai.aliyuncs.com/magic-mirror-pdf/mp3/wdyy.mp3',
  },
  
  onReady: function () {
    this.AudioContext = wx.createAudioContext('myAudio');
  },
// 手动播放音频文件
  audioClick() {
    this.setData({
      isPlaying: !this.data.isPlaying
    })
    if (this.data.isPlaying) {
      this.AudioContext.play();
    } else {
      this.AudioContext.pause();
    }
  },

结果如下:
在这里插入图片描述
点击就可以实现播放和暂停
有一点需要注意:进页面之后 ,音频加载是需要时间的,加载完才能播放

2、微信小程序wx.createInnerAudioContext使用方法

实现原理:

创建一个音频组件,然后播放(常用于播放背景音乐,加载完音频直接播放)

//index.js
const app = getApp()
// 1、创建audio对象
const myaudio = wx.createInnerAudioContext();
Page({
  data: {
    isplay: false,// 是否播放
  },
  
  onShow: function () {
    // 2、设置播放链接
    myaudio.src = 'https://magic-mirror-oss.oss-cn-shanghai.aliyuncs.com/magic-mirror-pdf/mp3/wdyy.mp3';
  },
  
  == 4、监听事件,在onLoad或onshow中设置== 
  onLoad: function () {
    myaudio.onPause(function () {
      wx.showToast({
        title: '暂停了',
      })
    })
  },
  
  == 3、为页面注册方法,播放暂停重播 ==
  
  //播放
  play: function () {
    myaudio.play();
    console.log(myaudio.duration);
    this.setData({
      isplay: true
    });
  },
  
  // 停止
  stop: function () {
    myaudio.pause();
    this.setData({
      isplay: false
    });
  },
  
 // 重播
  review: function () {
    myaudio.stop();
    myaudio.play()
    this.setData({
      isplay: true
    });
  }
  
})

页面:

<view class='audioContainer'>
  <view>录音</view>
  <!--当前为停止状态  -->
  <view class='audioImg' wx:if="{{isplay==false}}" bindtap='play'>
    播放
  </view>
  <!--当前为播放状态  -->
  <view class='audioImg'  wx:if="{{isplay==true}}" bindtap='stop'>
   暂停
  </view>
</view>
<view style='width:50%'>
<button bindtap='review' type='primary'>重新播放</button>
</view>

***如果有多条录音,开头可定义多个对象
const myaudio = wx.createInnerAudioContext({});
const myaudio2 = wx.createInnerAudioContext({});
...
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值