I'm making an audio app with jQuery mobile which is compiled with phonegap build. The audio plays correctly as it should, but the problem is when an audio is playing and you tap on a new audio to play. The first audio doesn't stop but still continues to play with the second one too. I want to know how I could find a way to stop the first audio playing when a user taps on the second audio file.
// JavaScript Document
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function play2face() {
playAudio(cordova.file.applicationDirectory + "www/music/audio1.mp3");
}
function playras() {
playAudio(cordova.file.applicationDirectory + "www/music/audio2.mp3");
}
function playbecca() {
playAudio(cordova.file.applicationDirectory + "www/music/audio3.mp3");
}
// Audio player
//
var my_media = null;
var mediaTimer = null;
// Play audio
//
function playAudio(src) {
// Create Media object from src
my_media = new Media(src, onSuccess, onError);
// 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);
}
}
// Pause audio
//
function pauseAudio() {
if (my_media) {
this.my_media.pause();
}
}
// Stop audio
//
function stopAudio() {
if (my_media) {
this.my_media.stop();
}
clearInterval(mediaTimer);
mediaTimer = null;
}
// onSuccess Callback
//
function onSuccess() {
console.log("playAudio():Audio Success");
}
// onError Callback
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
// Set audio position
//
function setAudioPosition(position) {
document.getElementById('audio_position').innerHTML = position;
}
HTML
Play Music | Pause Music | Stop Music
Play Music | Pause Music | Stop Music
Play Music | Pause Music | Stop Music
Put a call to stopAudio()
at the top of the playAudio(src)
funtion?
Like so:
function playAudio(src) {
stopAudio();
//rest of your function
}