前几天在小程序中使用音频时发现一个问题:音频只能在模拟器中播放,
在这里写下两种解决的方法:
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({});
...