I've been messing around with programming a test app for android and I've come across a issue playing a audio file. My problem lies with as soon as the page loads the audio file plays when it's not meant to and doesn't play via a button click
I'm using the example for cordova to get the audio to play but I can't work out why the audio plays straight away
Thanks
Script
script type="text/javascript" charset="utf-8" src="cordova-2.2.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
playAudio("/android_asset/www/audio/audio.mp3");
}
// Audio player
//
var my_media = null;
var mediaTimer = null;
function playAudio(src) {
if (my_media == null) {
// Create Media object from src
my_media = new Media(src, onSuccess, onError);
} // else play current audio
// Play audio
my_media.play();
// Update my_media position every second
if (mediaTimer == null) {
mediaTimer = setInterval(function() {
// get my_media position
my_media.getCurrentPosition(
// success callback
function(position) {
if (position > -1) {
setAudioPosition((position) + " sec");
}
},
// error callback
function(e) {
console.log("Error getting pos=" + e);
setAudioPosition("Error: " + e);
}
);
}, 1000);
}
}
</script>
HTML button click
<a class="button" onclick="playaudio('/android_asset/www/audio/audio.mp3')";>Play that audio!</a>
Because onDeviceReady() is listener callback for addEventListener.
So whenever this listener instantiate your onDeviceReady() method will be called automatically.
And from that method you are calling playAudio() method, that's why your audio start playing automatically.
Remove this playAudio() method call from the onDeviceReady() callback function.
EDIT:
change this
<a class="button" onclick="playaudio('/android_asset/www/audio/audio.mp3')";>Play that audio!</a>
with,
<a class="button" onclick="playAudio('/android_asset/www/audio/audio.mp3');">Play that audio!</a>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With