uniapp 之 base64转临时地址播放mp3
需求是:进入页面的时候是先有背景音乐,发送问题请求回答的时候会返回文字和音频,前端要把音频读出来,并且把背景音乐停止,读完音频后再打开背景音乐
一开始用的直接base64直接拼接在地址后 真机放不了
const innerAudioContext = wx.createInnerAudioContext();
innerAudioContext.src ='data:audio/mp3;base64,'+ 请求获取的base64编码的mp3格式文件;
innerAudioContext.play();
下面这个方式亲测有效
//背景音乐
playBackground(innerAudioContext, stop) {
// const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = true;
innerAudioContext.loop = true; //循环播放
innerAudioContext.src = 'https://wealthgod.oss-cn-beijing.aliyuncs.com/caishen/backgroundmq3.mp3';
innerAudioContext.onPlay(() => {
console.log('开始播放');
});
innerAudioContext.onStop((res) => {
innerAudioContext.stop()
//播放停止,销毁该实例
innerAudioContext.destroy()
});
innerAudioContext.onEnded((res) => {
innerAudioContext.play();
});
},
//回答音频
playerAnswer(url) {
const backgroundAudioManager = wx.getBackgroundAudioManager()
var number = Math.random()
const audioPath = wx.env.USER_DATA_PATH + '/new' + number + '.mp3'
const fs = wx.getFileSystemManager();
fs.writeFile({
filePath: audioPath,
data: url,
encoding: 'base64',
success(res) {
backgroundAudioManager.title = '财神'
backgroundAudioManager.src = audioPath
backgroundAudioManager.onEnded((res) => {
backgroundAudioManager.src = 'https://wealthgod.oss-cn-beijing.aliyuncs.com/caishen/backgroundmq3.mp3';
});
},
})
},
this.playBackground(uni.createInnerAudioContext())
this.playerAnswer(surl)//surl是背景地址
//manifest.json中
/* 小程序特有相关 */
"mp-weixin" : {
"requiredBackgroundModes" : [ "audio" ],
},