[劉陽Java]_酷炫視頻播放器製做_JS篇

此文章是接着上次寫的《酷炫視頻播放器製做_界面篇》將其完善,咱們主要給你們介紹一下如何利用JS腳原本控制視頻的播放。爲了讓你們可以保持對要完成的功能有直接的瞭解,咱們仍是將效果圖附到文章裏面css

完成本篇文章的代碼編寫,你能GET到200+代碼量,且可以掌握不少有關video標籤的屬性,函數,事件的應用。固然但願你們也多多鼓勵我寫出更多更實際的文章來幫助你們學習的提高html

第一步:咱們先簡單實現播放與暫停的效果,爲了整個界面的DOM操做簡單一點,咱們就用jQuery來配合界面的操做java

$(function() {
    var playVideo = $("video"); // 獲取播放視頻對象
    var playPause = $(".playPause"); // 獲取播放與暫停
    var currentTime = $(".timebar .currentTime"); // 當前時間
    var duration = $(".timebar .duration"); // 總時間
    var progress = $(".timebar .progress-bar"); // 進度條
    var volumebar = $(".volumeBar .volumewrap").find(".progress-bar"); // 音量控制進度條
    playVideo[0].volume = 0.4; // 初始化音量
    
    // 播放按鈕點擊事件,目的控制視頻播放與暫停
    playPause.on("click", function() {
        playControl();
    });
    // 屏幕點擊事件,目的控制視頻播放與暫定
    $(".playContent").on("click", function() {
        playControl();
    });
    
    /**
     * 控制播放的函數
     */
    function playControl() {
        // 切換播放按鈕的樣式        
        playPause.toggleClass('playIcon');
        if(playVideo[0].paused) {
            playVideo[0].play();
        } else {
            playVideo[0].pause();
        }
    }
});

 第二步:計算視頻時長,時長的顯示標準:小時:分鐘:妙。這裏咱們會H5中video標籤的duration屬性,此屬性返回視頻的時長,時長計量單位秒web

/**
 * 將視頻時長轉化爲時間:小時,分鐘,秒
 * @param {Object} value
 */
function formatSeconds(value) {
    value = parseInt(value);
    var time; // 存儲轉化好的時間格式
    if(value > -1) {
        hour = Math.floor(value / 3600); // 1小時=3600秒
        min = Math.floor(value / 60) % 60; // 1分鐘=60秒 
        sec = value % 60;
        day = parseInt(hour / 24);
        if(day > 0) {
            hour = hour - 24 * day;
            time = day + "day " + hour + ":";
        } else {
            time = hour + ":";
        }
        if (min < 0) {
            time += "0"
        }
        time += min + ":";
        if (sec < 0) {
            time += "0";
        }
        time += sec;
    }
    return time;
}

 第三步:設置視頻加載後將視頻時長顯示到頁面上。這裏會用到video標籤的onloadedmetadata事件瀏覽器

/**
 * 視頻加載結束後觸發loadedmetadata事件
 * onloadedmetadata 事件在指定視頻/音頻(audio/video)的元數據加載後觸發
 * 視頻/音頻(audio/video)的元數據包含: 時長,尺寸大小(視頻),文本軌道
 */
playVideo.on("loadedmetadata", function() {
    duration.text(formatSeconds(playVideo[0].duration));
});

 第四步:視頻進度條更新,完成視頻播放時候進度條不斷加載播放進度。這裏會用到video標籤的timeupdate事件ide

/**
 * ontimeupdate 事件在視頻/音頻(audio/video)當前的播放位置發送改變時觸發
 * 該事件一般與 Video 對象的 currentTime 屬性一塊兒使用, 該屬性返回視頻/音頻(audio/video)的當前播放位置
 */
playVideo.on("timeupdate", function() {
    currentTime.text(formatSeconds(playVideo[0].currentTime));
    progress.css("width", 100 * playVideo[0].currentTime / playVideo[0].duration + "%");
});

 第五步:視頻播放完成須要完成的更新操做。這裏會用到video標籤的ended事件函數

/**
 * ended 事件在音頻/視頻(audio/video)播放完成後觸發
 */
playVideo.on('ended', function() {
    playPause.toggleClass('playIcon');
});

 第六步:視頻全屏播放,這裏考慮兼容不一樣瀏覽器的內核(webkit,moz,ie)。同時還會用到video標籤的requestFullscreen屬性來判斷全屏模式,document元素的exitFullScreen來退出全屏等功能設置學習

/**
 * 視頻全屏播放
 * 這裏儘可能作到IE,Chrome,moz的內核的瀏覽器全屏播放的兼容性
 */
$('.fullScreen').on('click', function() {
    if ($(this).hasClass('cancleScreen')) {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.mozExitFullScreen) {
            document.mozExitFullScreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        }
        $(this).removeClass('cancleScreen');
        $('#willesPlay .playControll').css({
            'bottom': -48
        }).removeClass('fullControll');
    } else {
        if (playVideo[0].requestFullscreen) {
            playVideo[0].requestFullscreen();
        } else if (playVideo[0].mozRequestFullScreen) {
            playVideo[0].mozRequestFullScreen();
        } else if (playVideo[0].webkitRequestFullscreen) {
            playVideo[0].webkitRequestFullscreen();
        } else if (playVideo[0].msRequestFullscreen) {
            playVideo[0].msRequestFullscreen();
        }
        $(this).addClass('cancleScreen');
        $('#willesPlay .playControll').css({
            'left': 0,
            'bottom': 0
        }).addClass('fullControll');
    }
    return false;
});

 第七步:調整播放進度代碼實現,思路以下this

  • 經過offset().left獲取進度條的座標位置
  • 經過鼠標點擊進度條座標-進度條初始座標位置=拉動進度條的偏移量(真實拉動距離)
  • 最後計算進度條的百分比,而後再轉化爲視頻拉動的時間
/**
 * 拉動時間軸,調整播放的進度
 */
$(".timebar .progress").mousedown(function(e) {
    e = e || window.event;
    updatebar(e.pageX);
});
    
/**
 * 調整播放進度代碼實現
 * 經過offset().left獲取進度條的座標位置
 * 經過鼠標點擊進度條座標-進度條初始座標位置=拉動進度條的偏移量(真實拉動距離)
 * 最後計算進度條的百分比,而後再轉化爲視頻拉動的時間
 */
var updatebar = function(x) {
    var maxduration = playVideo[0].duration; // 總時長
    var positions = x - progress.offset().left; // 拉動進度條的偏移量
    var percentage = 100 * positions / $(".timebar .progress").width();
    if(percentage > 100) {
        percentage = 100;
    }
    if (percentage < 0) {
        percentage = 0;
    }
    progress.css("width", percentage + "%");
    playVideo[0].currentTime = maxduration * percentage / 100;
}

 第八步:音量調整與控制spa

/**
 * 音量控制彈出窗
 */
$(".volume").on("click", function(e) {
    e = e || window.event;
    $(".volumeBar").toggle();
    e.stopPropagation();
});
    
/**
 * 音量控制事件監聽
 * 多事件綁定:點擊,鼠標滾輪等等方式來操做音量控制
 */
$(".volumeBar").on('click mousewhell DOMMouseScroll', function(e){
    e = e || window.event;
    volumeControl(e); // 控制音量調整的核心代碼
    e.stopPropagation();
    return false;
});
    
/**
 * 控制音量調整的核心代碼
 * @param {Object} e
 */
function volumeControl(e) {
    e = e || window.event;
    var eventype = e.type;
    var delta = (e.originalEvent.wheelDelta && (e.originalEvent.wheelDelta > 0 ? 1 : -1)) || (e.originalEvent.detail && (e.originalEvent.detail > 0 ? -1 : 1));
    var positions = 0;
    var percentage = 0;
    if (eventype == "click") {
        positions = volumebar.offset().top - e.pageY;
        percentage = 100 * (positions + volumebar.height()) / $('.volumeBar .volumewrap').height();
    } else if (eventype == "mousewheel" || eventype == "DOMMouseScroll") {
        percentage = 100 * (volumebar.height() + delta) / $('.volumeBar .volumewrap').height();
    }
    if (percentage < 0) {
        percentage = 0;
        $('.otherControl .volume').attr('class', 'volume glyphicon glyphicon-volume-off');
    }
    if (percentage > 50) {
        $('.otherControl .volume').attr('class', 'volume glyphicon glyphicon-volume-up');
    }
    if (percentage > 0 && percentage <= 50) {
        $('.otherControl .volume').attr('class', 'volume glyphicon glyphicon-volume-down');
    }
    if (percentage >= 100) {
        percentage = 100;
    }
    $('.volumewrap .progress-bar').css('height', percentage + '%');
    playVideo[0].volume = percentage / 100;
    e.stopPropagation();
    e.preventDefault();
}

最後仍是舒適給出完整代碼,供你們分享與預覽,甚至拷貝均可以哈,槓槓得。。。

$(function() {
    var playVideo = $("video"); // 獲取播放視頻對象
    var playPause = $(".playPause"); // 獲取播放與暫停
    var currentTime = $(".timebar .currentTime"); // 當前時間
    var duration = $(".timebar .duration"); // 總時間
    var progress = $(".timebar .progress-bar"); // 進度條
    var volumebar = $(".volumeBar .volumewrap").find(".progress-bar"); // 音量控制進度條
    playVideo[0].volume = 0.4; // 初始化音量
    
    // 播放按鈕點擊事件,目的控制視頻播放與暫停
    playPause.on("click", function() {
        playControl();
    });
    // 屏幕點擊事件,目的控制視頻播放與暫定
    $(".playContent").on("click", function() {
        playControl();
        formatSeconds(playVideo[0].duration);
    });
    
    /**
     * 控制播放的函數
     */
    function playControl() {
        // 切換播放按鈕的樣式        
        playPause.toggleClass('playIcon');
        if(playVideo[0].paused) {
            playVideo[0].play();
        } else {
            playVideo[0].pause();
        }
    }
    
    /**
     * 點擊網頁任何地方讓音量調節窗口關閉
     */
    $(document).click(function() {
        $(".volumeBar").hide();
    });
    
    /**
     * 視頻加載結束後觸發loadedmetadata事件
     * onloadedmetadata 事件在指定視頻/音頻(audio/video)的元數據加載後觸發
     * 視頻/音頻(audio/video)的元數據包含: 時長,尺寸大小(視頻),文本軌道
     */
    playVideo.on("loadedmetadata", function() {
        duration.text(formatSeconds(playVideo[0].duration));
    });
    
    /**
     * ontimeupdate 事件在視頻/音頻(audio/video)當前的播放位置發送改變時觸發
     * 該事件一般與 Video 對象的 currentTime 屬性一塊兒使用, 該屬性返回視頻/音頻(audio/video)的當前播放位置
     */
    playVideo.on("timeupdate", function() {
        currentTime.text(formatSeconds(playVideo[0].currentTime));
        progress.css("width", 100 * playVideo[0].currentTime / playVideo[0].duration + "%");
    });
    
    /**
     * ended 事件在音頻/視頻(audio/video)播放完成後觸發
     */
    playVideo.on('ended', function() {
        playPause.toggleClass('playIcon');
    });
    
    /**
     * 視頻全屏播放
     * 這裏儘可能作到IE,Chrome,moz的內核的瀏覽器全屏播放的兼容性
     */
    $('.fullScreen').on('click', function() {
        if ($(this).hasClass('cancleScreen')) {
            if (document.exitFullscreen) {
                document.exitFullscreen();
            } else if (document.mozExitFullScreen) {
                document.mozExitFullScreen();
            } else if (document.webkitExitFullscreen) {
                document.webkitExitFullscreen();
            }
            $(this).removeClass('cancleScreen');
            $('#willesPlay .playControll').css({
                'bottom': -48
            }).removeClass('fullControll');
        } else {
            if (playVideo[0].requestFullscreen) {
                playVideo[0].requestFullscreen();
            } else if (playVideo[0].mozRequestFullScreen) {
                playVideo[0].mozRequestFullScreen();
            } else if (playVideo[0].webkitRequestFullscreen) {
                playVideo[0].webkitRequestFullscreen();
            } else if (playVideo[0].msRequestFullscreen) {
                playVideo[0].msRequestFullscreen();
            }
            $(this).addClass('cancleScreen');
            $('#willesPlay .playControll').css({
                'left': 0,
                'bottom': 0
            }).addClass('fullControll');
        }
        return false;
    });
    
    /**
     * 拉動時間軸,調整播放的進度
     */
    $(".timebar .progress").mousedown(function(e) {
        e = e || window.event;
        updatebar(e.pageX);
    });
    
    /**
     * 調整播放進度代碼實現
     * 經過offset().left獲取進度條的座標位置
     * 經過鼠標點擊進度條座標-進度條初始座標位置=拉動進度條的偏移量(真實拉動距離)
     * 最後計算進度條的百分比,而後再轉化爲視頻拉動的時間
     */
    var updatebar = function(x) {
        var maxduration = playVideo[0].duration; // 總時長
        var positions = x - progress.offset().left; // 拉動進度條的偏移量
        var percentage = 100 * positions / $(".timebar .progress").width();
        if(percentage > 100) {
            percentage = 100;
        }
        if (percentage < 0) {
            percentage = 0;
        }
        progress.css("width", percentage + "%");
        playVideo[0].currentTime = maxduration * percentage / 100;
    }
    
    /**
     * 音量控制彈出窗
     */
    $(".volume").on("click", function(e) {
        e = e || window.event;
        $(".volumeBar").toggle();
        e.stopPropagation();
    });
    
    /**
     * 音量控制事件監聽
     * 多事件綁定:點擊,鼠標滾輪等等方式來操做音量控制
     */
    $(".volumeBar").on('click mousewhell DOMMouseScroll', function(e){
        e = e || window.event;
        volumeControl(e); // 控制音量調整的核心代碼
        e.stopPropagation();
        return false;
    });
    
    /**
     * 控制音量調整的核心代碼
     * @param {Object} e
     */
    function volumeControl(e) {
        e = e || window.event;
        var eventype = e.type;
        var delta = (e.originalEvent.wheelDelta && (e.originalEvent.wheelDelta > 0 ? 1 : -1)) || (e.originalEvent.detail && (e.originalEvent.detail > 0 ? -1 : 1));
        var positions = 0;
        var percentage = 0;
        if (eventype == "click") {
            positions = volumebar.offset().top - e.pageY;
            percentage = 100 * (positions + volumebar.height()) / $('.volumeBar .volumewrap').height();
        } else if (eventype == "mousewheel" || eventype == "DOMMouseScroll") {
            percentage = 100 * (volumebar.height() + delta) / $('.volumeBar .volumewrap').height();
        }
        if (percentage < 0) {
            percentage = 0;
            $('.otherControl .volume').attr('class', 'volume glyphicon glyphicon-volume-off');
        }
        if (percentage > 50) {
            $('.otherControl .volume').attr('class', 'volume glyphicon glyphicon-volume-up');
        }
        if (percentage > 0 && percentage <= 50) {
            $('.otherControl .volume').attr('class', 'volume glyphicon glyphicon-volume-down');
        }
        if (percentage >= 100) {
            percentage = 100;
        }
        $('.volumewrap .progress-bar').css('height', percentage + '%');
        playVideo[0].volume = percentage / 100;
        e.stopPropagation();
        e.preventDefault();
    }
});

/**
 * 將視頻時長轉化爲時間:小時,分鐘,秒
 * @param {Object} value
 */
function formatSeconds(value) {
    value = parseInt(value);
    var time; // 存儲轉化好的時間格式
    if(value > -1) {
        hour = Math.floor(value / 3600); // 1小時=3600秒
        min = Math.floor(value / 60) % 60; // 1分鐘=60秒 
        sec = value % 60;
        day = parseInt(hour / 24);
        if(day > 0) {
            hour = hour - 24 * day;
            time = day + "day " + hour + ":";
        } else {
            time = hour + ":";
        }
        if (min < 0) {
            time += "0"
        }
        time += min + ":";
        if (sec < 0) {
            time += "0";
        }
        time += sec;
    }
    return time;
}
相關文章
相關標籤/搜索