如何以编程方式获取正在播放的YouTube视频的字幕?

最初,我尝试通过YouTube API离线进行操作,但是as it seems YouTube禁止获取您不是所有者的视频的字幕。

现在,我正在尝试在线进行。我没有找到用于字幕的YouTube Player Api方法,也没有尝试通过videojs中的the way it could be done for usual videos播放器将YouTube字幕作为TextTrack获得,但以下方法不起作用:

<html>
<head>
<link href="//vjs.zencdn.net/4.12/video-js.css" rel="stylesheet">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="//vjs.zencdn.net/4.12/video.js"></script>
<script type="text/javascript" src="../lib/youtube.js"></script>
</head>

<body>
<video  id="myvideo"
        class="video-js vjs-default-skin vjs-big-play-centered"
        controls
        preload="auto"
        width="640"
        height="360">
</video>

<script type="text/javascript">
    var myvideo = videojs(
        "myvideo",
        {
            "techOrder": ["youtube"],
            "src": "https://www.youtube.com/watch?v=jNhtbmXzIaM"
        },
        function() {
            console.log('Tracks: ' + this.textTracks().length); //zero here :(

            /*var aTextTrack = this.textTracks()[0];
            aTextTrack.on('loaded', function() {
                console.log('here it is');
                cues = aTextTrack.cues();
                console.log('Ready State', aTextTrack.readyState())
                console.log('Cues', cues);
            });
            aTextTrack.show();*/
        });
</script>
</body>
</html>

我还尝试了一种解析YouTube Player IFrame(内部带有当前字幕行的div)的丑陋解决方案,但是由于源不匹配的安全性问题,它无法正常工作。

用Java(对于离线解决方案)或javascript(对于在线解决方案)可以实现我的目标吗?

最佳答案

我如何从youtube视频中获取字幕是通过向此网址发出一个简单的请求https://video.google.com/timedtext?lang= {LANG}&v = {videoId}

我尝试使用Youtube API v3,但目前无法正常工作。当您对某个视频使用YouTube API v3发出请求时,您需要上传视频的人批准字幕的下载,否则请在控制台中显示403错误。出现错误是正常现象,服务器未收到批准,因此返回错误。

您可以使用Youtube API v3从自己的视频中下载字幕。

与此类似的工作就可以了。响应将采用XML格式:

   $.ajax({
        type: "POST",
        url: "https://video.google.com/timedtext?lang=en&v=5MgBikgcWnY"
    }).done(function (response) {
        console.log(response);
    }).fail(function (response) {
        console.log();
    });

07-24 09:44
查看更多