利用html5实现类似微信的手机摇一摇功能,并播放音乐。
1、 deviceOrientation:封装了方向传感器数据的事件,可以获取手机静止状态下的方向数据,例如手机所处角度、方位、朝向等。
2、 deviceMotion:封装了运动传感器数据的事件,可以获取手机运动状态下的运动加速度等数据。
<!DOCTYPE html>
<html lang="cn">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>摇一摇功能</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
// 首先在页面上要监听运动传感事件
function init(){
// 判断移动浏览器支持运动传感事件
if (window.DeviceMotionEvent) {
window.addEventListener('devicemotion',deviceMotionHandler, false);
}else{
alert('不支持移动事件');
}
}
var SHAKE_THRESHOLD = 3000; // 首先,定义一个摇动的阀值
var last_update = 0; // 定义一个变量保存上次更新的时间
var x=y=z=last_x=last_y=last_z=0; // 紧接着定义x、y、z记录三个轴的数据以及上一次出发的时间
var count = 0;
function deviceMotionHandler(eventData) {
var acceleration =eventData.accelerationIncludingGravity;
// 获取当前时间
var curTime = new Date().getTime();
var diffTime = curTime -last_update;
// 固定时间段
if (diffTime > 100) {
last_update = curTime;
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
var speed = Math.abs(x +y + z - last_x - last_y - last_z) / diffTime * 10000;
if (speed > SHAKE_THRESHOLD) {
// TODO:在此处可以实现摇一摇之后所要进行的数据逻辑操作
count++;
alert("摇动了");
alert("摇你妹!第" + count + "个了!");
}
last_x = x;
last_y = y;
last_z = z;
}
}
</script>
</head>
<body οnlοad="init()">
<p>用力摇一摇你手机</p>
<audio style="display:hiden" id="musicBox" preload="metadata" controls src="http://211.148.5.228:8002/Pages/test/Kalimba.mp3" autoplay="false">
</audio>
</body>
</html>