问题
Can i use jquery(or javascript) to force an html5 video player to play in picture in picture mode?(image below)
.
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