一种制作实时画中画的方法

A way to make a real time picture in picture

有件事困扰着我,我在这里大声呼救:

我想制作一个项目,其中有一个视频,如果我激活画中画形式,它会在主页和画中画页面上播放。

除了复制该视频元素别无他法...

您可以通过向克隆提供从原始视频生成的 MediaStream 并将该克隆用作 PiP 的源来使同步更好一些 window。

if( 1 && "pictureInPictureElement" in document ) {

const button = document.getElementById( "btn" );
const in_doc = document.getElementById( "in_doc" );
const clone = document.getElementById( "clone" );

in_doc.onloadedmetadata = (evt) => {
  const stream = in_doc.captureStream();
  // we stop the audio coming in the clone
  // otherwise wed have two audio feeds in the output
  // with few µs of delay, creating an horrible echo effect
  stream.getAudioTracks().forEach( track => track.stop() );
  // feed the clone with a MediaStream generated from in-doc video
  // they'll thus display the same images
  clone.srcObject = stream;
};

// our own UI
button.onclick = (evt) => {
  if( document.pictureInPictureElement === clone ) {
    clone.pause();
    document.exitPictureInPicture()
  }
  else {
    clone.play();
    clone.requestPictureInPicture();
  }
};

// handle the default UI
in_doc.addEventListener( 'enterpictureinpicture', (evt) => {
  if( document.pictureInPictureElement === clone ) {
    // already active
    return;
  }
  else {
    // there can be only only one PiP window at a time
    clone.play();
    clone.requestPictureInPicture();
  }
} );

}
else {
  console.error( "Your browser doesn't support the PiP API." );
  console.error( "This demo won't work for you." );
}
#clone {
  visibility: hidden;
  position: absolute;
  pointer-events: none;
}
video {
  height: 100vh;
  vertical-align: top;
}
<button id="btn" >toggle PiP</button>
<video id="in_doc" controls src="https://upload.wikimedia.org/wikipedia/commons/2/22/Volcano_Lava_Sample.webm" crossorigin ></video>
<!-- The following will be hidden and only used to generate the PiP -->
<video id="clone" autoplay ></video>

另请注意,虽然目前 Chrome 的 UI 未对 PiP window 设置任何控件,但他们将来可能会添加一些控件,并且其他实现可能(例如 Firefox 自己的画中画,它不是 API 画中画,它有一个 play/pause 按钮)。 因此,为了面向未来,您可能希望 link 用户触发的所有媒体事件(播放、暂停、搜索等)从克隆到可见视频。