html5 web 摇一摇切换歌曲
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="utf-8" /> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0" /> 6 <title>摇一摇功能</title> 7 </head> 8 <body onload="init()"> 9 <p>用力摇一摇你手机</p> 10 <audio id="musicBox" controls src=""/> 11 </body> 12 </html> 13 <script type="text/javascript"> 14 //Javascript 15 var SHAKE_THRESHOLD = 3000; 16 var last_update = 0; 17 var x = y = z = last_x = last_y = last_z = 0; 18 function init() { 19 if (window.DeviceMotionEvent) { 20 window.addEventListener(‘devicemotion‘, deviceMotionHandler, false); 21 } else { 22 alert(‘not support mobile event‘); 23 } 24 } 25 function deviceMotionHandler(eventData) { 26 var acceleration = eventData.accelerationIncludingGravity; 27 var curTime = new Date().getTime(); 28 if ((curTime - last_update) > 100) { 29 var diffTime = curTime - last_update; 30 last_update = curTime; 31 x = acceleration.x; 32 y = acceleration.y; 33 z = acceleration.z; 34 var speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000; 35 36 if (speed > SHAKE_THRESHOLD) { 37 alert("摇动了,播放"); 38 var media=document.getElementById("musicBox");//获取音频控件 39 media.setAttribute("src","http://1.html5weby1y.sinaapp.com/2.mp3"); 40 media.load();//加载音频 41 media.play();//播放音频 42 } 43 last_x = x; 44 last_y = y; 45 last_z = z; 46 } 47 } 48 </script>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。