Playing audio with phonegap and cordova for Android
I was messing around with programming an android test app and I ran into an audio file playback issue. My problem is that as soon as the page loads the sound file when it is not intended and does not play on a button click
I am using the example for cordova to play the sound, but I cannot figure out why the sound is playing right now
thank
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>
Click the HTML button
<a class="button" onclick="playaudio('/android_asset/www/audio/audio.mp3')";>Play that audio!</a>
source to share
Because it onDeviceReady()
is a listener callback for addEventListener
.
So, whenever this executor creates an instance of your method onDeviceReady()
, it gets called automatically.
And from that method, you call the method playAudio()
, so your sound starts playing automatically.
Remove this method call playAudio()
from the callback function onDeviceReady()
.
EDIT:
change this value
<a class="button" onclick="playaudio('/android_asset/www/audio/audio.mp3')";>Play that audio!</a>
from,
<a class="button" onclick="playAudio('/android_asset/www/audio/audio.mp3');">Play that audio!</a>
source to share