jPlayer - 通过Javascript实现回滚功能

时间:2012-08-03 21:13:46

标签: javascript jquery audio keypress jplayer

我使用 jPlayer 遇到了一个问题,我在搜索了几个地方之后想到它会在这里得到足够的使用,而且有人肯定会遇到类似问题问题。

我正在使用jPlayer播放音频文件,我的用户希望通过特定的热键快进和快退功能。我注意到jPlayer不提供开箱即用的功能(它只通过点击当前的进度条来处理快进和快退

理想情况下 - 所有必要的都是单个按键来切换快进(或倒带)。再次按下相同的键时,音频文件将根据当前位置开始播放。

1 个答案:

答案 0 :(得分:4)

我决定实现我自己的解决方案,目前似乎工作正常。我想如果其他人遇到这样的问题我会分享它。

原谅原油的实施。这只是一个概念证明:

必要的Javascript:

//Handles the key down event (so the user can hold a key down to continue)
$(document).keydown(function (e) {
    //Rewind
    if (e.keyCode == 37 && (!rewinding)) {
        rewinding = true;
        //Pause the player
        $("#player").jPlayer("pause");
        RewindTrack();
        rwaction = window.setInterval(function () { RewindTrack() }, 500);
    }
    else if (e.keyCode == 39 && (!fastforward)) {
        fastforward = true;
        //Pause the player
        $("#player").jPlayer("pause");
        FastforwardTrack();
        ffaction = window.setInterval(function () { FastforwardTrack() }, 500);
    }
});
//Ends the action
$(document).keyup(function (e) {
    //Rewind
    if (e.keyCode == 37) {
        rewinding = false;
        window.clearInterval(rwaction);
        $("#player").jPlayer("pause");
    }
    else if (e.keyCode == 39) {
        fastforward = false;
        window.clearInterval(ffaction);
        $("#player").jPlayer("pause");
    }
});

//Related function
function GetPlayerProgress() {
    return ($('.jp-play-bar').width() / $('.jp-seek-bar').width() * 100);
}

//Handles rewinding
function RewindTrack() {
    //Get current progress and decrement
    var currentProgress = GetPlayerProgress();
    //Rewinds 10% of track length
    var futureProgress = currentProgress - 10;
    //If it goes past the starting point - stop rewinding and pause
    if (futureProgress <= 0) {
        rewinding = false;
        window.clearInterval(rwaction);
        $("#player").jPlayer("pause", 0);
    }
    //Continue rewinding
    else {
        $("#player").jPlayer("playHead", parseInt(futureProgress, 10));
    }
}

//Fast forwards the track
function FastforwardTrack() {
    //Get current progress and increment
    var currentProgress = GetPlayerProgress();
    //Fast forwards 10%
    var futureProgress = currentProgress + 10;
    //If the percentage exceeds the max - stop fast forwarding at the end.
    if (futureProgress >= 100) {
        fastforward = false;
        window.clearInterval(ffaction);
        $("#player").jPlayer("playHead", parseInt($('.jp-duration').text().replace(':', '')));
    }
    else {
        $("#player").jPlayer("playHead", parseInt(futureProgress, 10));
    }
}

Working Demo (使用向左箭头表示快退,向右表示快进)