PhoneGap无法从Media API中获取Duration(),但其他方法也可以

fus*_*n27 8 javascript jquery jquery-mobile cordova

我正在构建一个带有PhoneGap的音频媒体记录器/播放器.这一切都很美妙,但我已经发现了一些我似乎无法解决的问题.

my_media.play();确实在我的Eclipse或XCode控制台中播放没有错误的媒体,这就是显示-1的警报令人费解的原因.我希望my_media.getDuration();返回我正在尝试播放的文件的持续时间.

我的try/catch块没有抛出错误,我对这个感到很困惑. 这是关于Media.getDuration()的PhoneGap文档.

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');
    });
}
Run Code Online (Sandbox Code Playgroud)

小智 2

当您调用 my_media.getDuration() 时,尚未加载相关媒体的元数据。在您的问题中引用的文档中,示例代码将 getDuration 调用放入一个间隔中:

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);
Run Code Online (Sandbox Code Playgroud)

我建议做类似的事情。