Vue--模仿微信摇一摇--音频播放的坑
let vm = new Vue({
data:{
timer_c: '',//动画定时器
timer_d:'',//数据请求定时器
lastTime:0,
lastX:0,
lastY:0,
lastZ:0,
shakeSpeed:3800,
animating:false,//是否动画
},
methods:{
shake(eventDate){
//获取设备加速度信息
var acceleration = eventDate.accelerationIncludingGravity;
var nowTime = new Date().getTime();
//如果这次摇的时间距离上次摇的时间有一定间隔 才执行
if(nowTime - this.lastTime > 100){
var diffTime = nowTime - this.lastTime;
this.lastTime = nowTime;
var x=0,y=0,z=0;
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
var speed = Math.abs(x + y + z - this.lastX - this.lastY - this.lastZ) / diffTime * 10000;
if(speed > this.shakeSpeed){
//判断是否登录
if(this.login==false){
this.$indicator.close();
this.AppLogin('{{ route('m.activityGame.shake').'?act=' }}'+app.request('act'));
return;
}
window.removeEventListener('devicemotion', this.shake, false);
this.$indicator.close();
this.is_operate = false;
if(this.timer_c){
clearTimeout(this.timer_c);
}
if(this.timer_d){
clearTimeout(this.timer_d);
};
document.getElementById('start').play();
this.animating = true;
this.timer_c = setTimeout(function(){
this.timer_d = setTimeout(function(){
window.removeEventListener('devicemotion', this.shake, false);
document.getElementById('end').play();
this.getAward();
},2000);
this.animating = false;
this.$indicator.open('开奖中...');
window.addEventListener('devicemotion', this.shake, false);
},1450)
}
this.lastX = x;
this.lastY = y;
this.lastZ = z;
}
},
},
mounted(){
//添加devicemotion事件
if(window.DeviceMotionEvent){
window.addEventListener('devicemotion', this.shake, false);
}else{
app.vm.$toast('本设备不支持摇一摇功能');
}
}
})
音频播放
ios App加载音频有延迟,解决办法:
//手动加载音频,解决ios App播放延迟的问题
let start=document.getElementById('start');
start.load();
audio兼容
ios系统下的浏览器播放音频或者视频时需要用户交互才可以
if (/i(Phone|P(o|a)d)/.test(navigator.userAgent)) {
$(document).one('touchstart',function(e) {
alert('touchstart');
document.getElementById('start').play();
document.getElementById('start').pause();
document.getElementById('end').play();
document.getElementById('end').pause();
});
}
微信浏览器做了特殊处理,可以不用交互
<script src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
autoPlayAudio2() {
wx.config({
// 配置信息, 即使不正确也能使用 wx.ready
debug: false,
appId: '',
timestamp: 1,
nonceStr: '',
signature: '',
jsApiList: []
});
wx.ready(function() {
var globalAudio_start=document.getElementById("start");
var globalAudio_end=document.getElementById("end");
globalAudio_start.play();
globalAudio_start.pause();
globalAudio_end.play();
globalAudio_end.pause();
});
}
这里需要注意是http还是https,如果生产环境是https,务必前缀是https,否则不起作用。
https://www.ibm.com/developerworks/cn/web/wa-ioshtml5/
https://segmentfault.com/q/1010000002500597
https://www.jianshu.com/p/b26cdf3a96f2?from=timeline
https://www.jianshu.com/p/21ac8ff7bac5