画中画模式
现在我们在播放视频,观看直播时有个功能可以将窗口缩小化,呈现视频的内容并播放声音,显示在屏幕角落中,这种模式叫"画中画模式"
官方称"Picture-in-picture",画中画提供了的API允许网站创建一个浮动的视频窗口总在最上面的其他窗口,以便用户可以继续消费与其他内容网站媒体互动时,他们的设备上或应用程序。利用webAPI实现如下的效果
API
在实现过程之前先了解画中画提供的API:
HTMLVideoElement:接口提供了用于操作视频对象的特殊属性和方法。它同时还继承了HTMLMediaElement 和 HTMLElement 的属性与方法。它提供了 autoPictureInPictureHTML 属性用于指示视频是否应该自动进入或离开画中画模式。
pictureInPictureElement:只读属性指出了画中画模式在本文档中,或null如果画中画模式不是目前使用,可判断当前文档中存不存在画中画模式
requestPictureInPicture:HTMLVideoElement 接口提供的 requestPictureInPicture() 方法会发出异步请求,并以画中画的模式显示视频。可用于调用画中画模式
exitPictureInPicture:请求视频包含在本文档中,目前浮动,是画中画模式,恢复以前的状态屏幕,用于退出画中画模式
enterpictureinpicture:该事件会在 HTMLVideoElement 成功进入画中画模式时触发。
leavepictureinpicture:该事件会在 HTMLVideoElement 成功离开画中画模式时触发。
PictureInPictureWindow:PictureInPictureWindow接口是一个对象,它可以通过编程的方式获得浮动视频窗口的宽度和高度,并调整浮动视频窗口的大小。
实现
//播放视频
<video
id="video"
width="640"
src="../video.mp4"
controls
ref="video"
></video>
<div>
//切换按钮
<el-button
type="primary"
icon="el-icon-document-copy"
ref="btn"
@click="toggle"
></el-button>
</div>
</div>
mounted() {
//首先获取video元素并注册事件
const video = this.$refs.video;
console.log(video);
video.addEventListener("enterpictureinpicture", this.enter);
video.addEventListener("leavepictureinpicture", this.leave);
},
//启用/关闭画中画模式
leave(content) {
console.log(content, "leave");
},
enter(content) {
console.log(content, "enter");
},
pipWindowChange(e) {
//当画中画窗口大小变化时
const pipWindow = e.target;
console.log(pipWindow.width, pipWindow.height);
},
async toggle() {
const video = this.$refs.video;
try {
//判断当前PictureInPicture是否开启并指向video元素
if (video !== document.pictureInPictureElement) {
//调用API开启画中画
await video.requestPictureInPicture();
// 启用画中画模式窗口变化
// video.requestPictureInPicture().then((pictureInPictureWindow) => {
// pictureInPictureWindow.onresize = this.pipWindowChange;
// });
} else {
//调用API关闭画中画
await document.exitPictureInPicture();
}
this.disable = true;
} catch (error) {
//错误处理
console.log(error);
} finally {
this.disable = false;
}
},
在开发过程中,常使用缩放播放听音频,好奇学习下实现方式,效果如上图,没整gif动图比较懒QAQ,共勉