html5 audio not triggered by acceleration on iPhone / pod
I want to trigger an audio file when I shake the iPhone. I can get audio to play with a button press. I can get audio to play on shake after I have first used the button press. But on first entry to the page shake accelerometer does not play the audio. Code is below and a little test page is at:
pineappleapps.com/zdev/html5test ((needs iPhone or iPod iOS v4.2 to test)
The scenarios are as follows:
1) refresh the page and tilt iPhone and play alert appears but no audio
2) press baseball button and alert appears then audio plays
3) now tilt the phone and alert appears and then audio plays
4) refresh the page again and tilt phone and again alert appears but no audio
Must be something to do with the button initializing the audio. Any help would be greatly appreciated.
Code:
javascript:
function baseball()
{
alert('play');
document.getElementById('bbaudio').play();
var t=setTimeout("enableShake()开发者_高级运维",3000);
}
function enableShake()
{
document.getElementById("shakeE").innerHTML = '1';
}
var ax = 0; var ay = 0; var shakemax = 0;
window.ondevicemotion = function(event)
{
ax = event.accelerationIncludingGravity.x;
ay = event.accelerationIncludingGravity.y;
az = event.accelerationIncludingGravity.z;
if(ax > shakemax)
{
shakemax = ax;
}
var shake = document.getElementById("shake");
shake.innerHTML = ax;
if(ax > 8.0)
{
var se = document.getElementById("shakeE").innerHTML;
if(se == '1')
{
document.getElementById("shakeE").innerHTML = '0';
baseball();
}
}
}
html:
<br />
<br />
<input type="submit" onclick="baseball()" value="baseball"/>
<br />
<br />
<br />
<br />
<div id="shake">0</div>
<div id="shakeE">1</div>
<audio id='bbaudio' src="baseball_hit.wav" controls="controls"></audio>
in this linked article, it says you can affect sounds by first loading them. I don't know if this works for sure since i haven't started developing for iPhone just yet. but i hope this helps!
精彩评论