I'm building out an audio media recorder/player with PhoneGap. It's all working beautifully, but I've hit a wrinkle I can't seem to iron.
my_media.play();
does indeed play the media w/o error in my Eclipse or XCode consoles which is why the alert that is showing a -1 is puzzling. I expect my_media.getDuration();
to return the duration of the file I'm attempting to play.
My try/catch block isn't throwing an error, I'm quite puzzled on this one. Here's the PhoneGap documentation on Media.getDuration().
function playAudio() {
$('#btnStopRecording').removeClass('ui-disabled');
$('#btnPlayMessage, #btnStartStopRecording, #btnDeleteMessage, #btnAcceptUpload').addClass('ui-disabled');
my_media = new Media(fullRecordPath,
// success callback
function () {
$('#btnPlayMessage, #btnStartStopRecording, #btnDeleteMessage, #btnAcceptUpload').removeClass('ui-disabled');
$('#btnStopRecording').addClass('ui-disabled');
},
// error callback
function (err) {
console.log("attempting to play fullRecordPath = "+fullRecordPath);
console.log("playAudio():Audio Error: " + err.code);
}
);
var thisDuration;
try{
thisDuration = my_media.getDuration();
} catch (err) {
console.log("attempting to get duration error code "+err.code);
console.log("attempting to get duration error message "+err.message);
}
alert("we're about play a file of this duration "+thisDuration);
my_media.play();
// stop playback when the stop button is tapped
$('#btnStopRecording').off('tap').on('tap',function()
{
my_media.stop();
$('#btnPlayMessage, #btnStartStopRecording, #btnDeleteMessage, #btnAcceptUpload').removeClass('ui-disabled');
$('#btnStopRecording').addClass('ui-disabled');
});
// if the user leaves the page, stop playback
$('#pageRecordMessage').live('pagehide', function()
{
my_media.stop();
$('#btnPlayMessage, #btnStartStopRecording, #btnDeleteMessage, #btnAcceptUpload').removeClass('ui-disabled');
$('#btnStopRecording').addClass('ui-disabled');
});
}
The metadata for the media in question has not been loaded when you call my_media.getDuration(). In the documentation you referenced in your question the example code puts the getDuration call into an interval:
var timerDur = setInterval(function() {
counter = counter + 100;
if (counter > 2000) {
clearInterval(timerDur);
}
var dur = my_media.getDuration();
if (dur > 0) {
clearInterval(timerDur);
document.getElementById('audio_duration').innerHTML = (dur) + " sec";
}
}, 100);
I would recommend doing something similar.
This solution works for me. Basically, play and immediately stop. It doesn't seem to take any time, seems like a decent workaround.
media.play();
media.stop();
var length = media.getDuration();
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