gpt4 book ai didi

javascript - Youtube Player Api 获取截图

转载 作者:行者123 更新时间:2023-12-03 08:26:42 27 4
gpt4 key购买 nike

有一个iframethis page我想从 video 获取屏幕截图标签,所以我必须到达 iframe 中的视频标签标签。

当我打开控制台并运行此代码时:

 const videoElement = document.getElementsByTagName('iframe')[0]
.contentWindow.document.getElementsByTagName('video')[0];

//Extracting picture from video tag
const canvas = document.createElement('canvas');
canvas.width = videoElement.videoWidth;
canvas.height = videoElement.videoHeight;
canvas.getContext('2d').drawImage(videoElement, 0, 0, canvas.width, canvas.height);

已抛出此错误:
Uncaught DOMException: Blocked a frame with origin "https://developers.google.com" from accessing a cross-origin frame.
at <anonymous>:1:57

另外,我检查了 this问题

我的问题是如何从 YouTube Player API 获取屏幕截图?

最佳答案

据我所知,无法从 YouTube Player API 截屏,因为它基于 iFrame。如果您想在自己的应用程序(不仅仅是浏览器扩展)中制作它们,则 CORS 将禁止此操作(您得到异常的原因)。

唯一的解决方法是使用可以从 YouTube 获得的数据将 YouTube 视频作为源放入视频 HTML 元素中。
这段代码应该很方便获取视频的源 URL:

class YoutubeVideo {

constructor(video_id, callback) {
return (async () => {
// You should also redirect those requests
// through your own API that would permit CORS
const response = await fetch(`https://www.youtube.com/get_video_info?video_id=${video_id}`, {
headers: { 'Content-Type' : 'text/plain'}
});
const video_info = await response.text();

let video = this.decodeQueryString(video_info);
if (video.status === 'fail') {
return callback(video);
}

if (video.url_encoded_fmt_stream_map)
video.source = this.decodeStreamMap(video.url_encoded_fmt_stream_map);

return callback(video);
})();
}

decodeQueryString(queryString) {
var key, keyValPair, keyValPairs, r, val, _i, _len;
r = {};
keyValPairs = queryString.split("&");
for (_i = 0, _len = keyValPairs.length; _i < _len; _i++) {
keyValPair = keyValPairs[_i];
key = decodeURIComponent(keyValPair.split("=")[0]);
val = decodeURIComponent(keyValPair.split("=")[1] || "");
r[key] = val;
}
return r;
}

decodeStreamMap(url_encoded_fmt_stream_map) {
var quality, sources, stream, type, urlEncodedStream, _i, _len, _ref;
sources = {};
_ref = url_encoded_fmt_stream_map.split(",");
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
urlEncodedStream = _ref[_i];
stream = this.decodeQueryString(urlEncodedStream);
type = stream.type.split(";")[0];
quality = stream.quality.split(",")[0];
stream.original_url = stream.url;
stream.url = "" + stream.url + "&signature=" + stream.sig;
sources["" + type + " " + quality] = stream;
}
return sources;
}
}


在构造函数中传递给回调的对象将具有 source 属性,其中包含所有可用视频类型和质量的源链接,您可以在浏览器的控制台上更好地检查它们。
然而,并不是所有的 YouTube 视频都可以这样处理,当你得到的只是禁止错误或空源时,我遇到了具有进一步限制的文件。

帮助我找到此解决方案的资源:
https://github.com/endlesshack/youtube-video

基于此解决方案工作的资源:
http://youtubescreenshot.com/

基于 expressjs 服务器的简单 Web App 概念证明:
https://github.com/RinSer/YouCut

关于javascript - Youtube Player Api 获取截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56299995/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com