beefast-mini-deliveryman/components/background-notice/index.js

126 lines
3.4 KiB
JavaScript

Component({
/**
* 组件的属性列表
*/
properties: {
start:{
type:Boolean,
value:false,
observer(s){
console.log(s);
if(s){
this.start();
}else{
this.stop();
}
}
}
},
/**
* 组件的初始数据
*/
data: {
emptyAudio:'',
haveOrderAudio:'',
initing:true
},
lifetimes:{
attached(){
this.data.initing = true;
this.downloadResource().then(()=>{
this.bgam = wx.getBackgroundAudioManager();
this.bgam.title = '后台通知';
this.bgam.audioType = 'music';
this.bgam.coverImgUrl = 'https://dman-1311994147.cos.ap-chengdu.myqcloud.com/static/logo_large.jpg';
this.bgam.onEnded(()=>{
this.bgam.src = this.data.emptyAudio;
});
this.bgam.onStop(()=>{
this.triggerEvent('stop')
});
this.triggerEvent('initSuccess');
}).catch(()=>{
this.triggerEvent('initError');
})
}
},
/**
* 组件的方法列表
*/
methods: {
async downloadResource(){
this.data.emptyAudio = `${wx.env.USER_DATA_PATH}/empty.wav`;
const emptyServerPath = 'https://dman-1311994147.cos.ap-chengdu.myqcloud.com/static/silence_file.wav';
this.data.haveOrderAudio = `${wx.env.USER_DATA_PATH}/haveorder.mp3`;
const haveOrderPath = 'https://dman-1311994147.cos.ap-chengdu.myqcloud.com/static/new_order.mp3';
await this.download(this.data.emptyAudio,emptyServerPath);
await this.download(this.data.haveOrderAudio,haveOrderPath);
},
async download(localPath,serverPath){
try {
//判断文件是否存在
const fs = wx.getFileSystemManager();
fs.accessSync(localPath);
} catch (error) {
await this.downloadFile(serverPath,localPath);
}
},
start(){
this.bgam.src = this.data.emptyAudio;
if(this.loopOrderTimer){
clearInterval(this.loopOrderTimer);
}
this.loopOrderTimer = setInterval(()=>{
this.triggerEvent('onTrigger');
},10000);
},
stop(){
if(this.loopOrderTimer){
clearInterval(this.loopOrderTimer);
}
if(this.bgam){
this.bgam.stop();
}
},
notice(){
//这里通知改为下面的inneraudio 之前用的上面的 但是突然有一天 在切换 src 之后会执行onStop
//从而导致停止播放音乐逻辑 不知道为什么 怀疑微信偷偷改东西或者手机问题
// this.bgam.src = this.data.haveOrderAudio;
// this.bgam.onEnded(()=>{
// this.bgam.src = this.data.emptyAudio;
// });
console.log('notice order');
const innerAudioContext = wx.createInnerAudioContext({
useWebAudioImplement:true
})
innerAudioContext.src = this.data.haveOrderAudio;
innerAudioContext.play();
innerAudioContext.onEnded(()=>{
innerAudioContext.destroy();
})
},
downloadFile(url,filePath){
console.log('download',url,filePath);
return new Promise((rs,rj)=>{
wx.downloadFile({
url: url,
filePath: filePath,
success: (result) => {
console.log('success',result);
rs()
},
fail: (res) => {
console.log('error',res.errMsg,url,filePath);
rj()
}
})
})
}
}
})