jQuery force html5 video to play “Picture in Picture” when “i” key is pressed

北城余情 提交于 2021-02-09 07:11:33

问题


Can i use jquery(or javascript) to force an html5 video player to play in picture in picture mode?(image below)

picture in picture.

This is for my personal site on which i'm using jquery 3.3.1(hosted by Google). For now i managed to use space bar to play/pause. This is my code so far:

<video id="player">
   <!-- source -->
</video>
<script>
player = $('#player')[0];

var player = $('#player')[0];
$(window).keydown(function(e) {
    switch(e.which){
        case(32):
            if(player.paused){
                player.play();
            } else{
                player.pause();
            }
        break; 
    }
});
</script>

Here is the code on CodePen.

The i key on keydown is 73


回答1:


This is possible, although obviously only in browsers which support PIP (at the time of this answer that's only Chrome 70 & 71).

To make it work listen for the i key in your switch. Then you can can call requestPictureInPicture() on the player to have it enter PIP mode. To make the toggle work when pressing i again you need to check the pictureInPictureElement property of the document. If it returns true, then PIP mode is already in use and you can end it by calling document.exitPictureInPicture(), like this:

var player = $("#player")[0];

$(window).keydown(function(e) {
  switch (e.which) {
    case 32:
      player.paused ? player.play() : player.pause();
      break;
    case 73:
      if (player.requestPictureInPicture) { // feature detection to stop errors in unsupported browsers
        if (document.pictureInPictureElement) {
          document.exitPictureInPicture();
        } else {
          player.requestPictureInPicture();
        }
      }
      break;
  }
});
video {
  width: 450px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<video id="player" controls>
  <source src="https://www.w3schools.com/howto/rain.mp4" type="video/mp4">
</video>

One caveat here is that after pressing i the focus is transferred to the PIP window, hence pressing i a second time appears to do nothing until you click on the browser window again to return focus so that the keydown listener can take effect.



来源:https://stackoverflow.com/questions/54005311/jquery-force-html5-video-to-play-picture-in-picture-when-i-key-is-pressed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!