4

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

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

4

1 回答 1

1

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

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

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 没有在画中画窗口上设置任何控件,但他们可能会在未来添加一些控件,并且其他实现可以(例如 Firefox 自己的画中画,它不是 API 的,有一个播放/暂停按钮) . 因此,为了未来的证明,您可能希望将用户触发的所有媒体事件(播放、暂停、搜索等)从克隆链接到可见视频。

于 2020-06-29T01:48:59.917 回答