可以,在onload事件中增加以下代码打开小程序就会自动播放音乐。
const myaudio = wx.createInnerAudioContext();注意:如果在ios下没声音,可能是以下几种问题导致:
myaudio.src = "http://repo.bfw.wiki/bfwrepo/sound/5c89fd22dea6948307.mp3"
myaudio.play();
方法一 : src里面的连接有中文的,可先通过 encodeURI 专门转码后再进行play()
innerAudioContext.src = encodeURI(voicePath);
方法二 : src没有中文的 使用autoplay 没有生效的话 可使用 play()方法 进行播放操作,如果play()不行 可加个定时器 延迟播放
const innerAudioContext = wx.createInnerAudioContext();
innerAudioContext.autoplay = true;
innerAudioContext.src = src;
innerAudioContext.loop = true;
innerAudioContext.onPlay(() => {
console.log('开始播放')
})
innerAudioContext.onStop((res) => {
console.log('停止播放')
});
// 第一种
innerAudioContext.play();
// 第二种 如果第一种没有效果
setTimeout(() => {
innerAudioContext.play();
}, 10);
方法三 : 因为小程序默认是根据系统的静音模式变动的 需要我们设置 obeyMuteSwitch 为false,这样就可以在静音模式下也有声音,在APP.JS的onLaunch生命周期配置一下
// ios端音频不能在静音下播放处理
wx.setInnerAudioOption({
obeyMuteSwitch: false,
success: function (res) {
console.log("开启静音模式下播放音乐的功能");
},
fail: function (err) {
console.log("静音设置失败");
},
});
网友回复