GouriSankar Sahu
GouriSankar Sahu

Reputation: 115

Get Subtitles data of a Youtube video using api in nodejs

Here is some link which provides subtitle list of youtube video in xml format.

'https://www.youtube.com/api/timedtext?lang=en&v=6dlr-1Qk8Uc'

'http://video.google.com/timedtext?type=track&v=zenMEj0cAC4&id=0&lang=en'

But it is not applied for all videos. Some videos have subtitle(cc) icon at bottom of video and on click this subtitle appears, but this links cannot return the subtitle data.

Then I have checked the respose data on click the cc icon , it return data of all videos which have subtitle.

But I cannot get how to call this api using node js.

Upvotes: 2

Views: 2966

Answers (1)

Mauricio Arias Olave
Mauricio Arias Olave

Reputation: 2575

UPDATE: 13/02/2025 - code below no longer works - API endpoint no longer available.


Instead of use the YouTube Data API - caption1 for retrieve the captions of a video, you can also use an AJAX callback for get the captions.

1If you want use the YouTube Data API for query the captions, I advise you read the documentation carefully.


In this example, an AJAX callback is used for retrieve the captions from a given YouTube video.

Using the XML parser, the response of the previous AJAX callback is iterated in a for-loop for get the captions:

// Ajax callback to the YouTube channel:
$.ajax({
  type: "GET",
  url: "http://video.google.com/timedtext?type=track&v=zenMEj0cAC4&id=0&lang=en",
  crossDomain: true,
}).done(function(data) {
  getCaption(data);
});

// Variables.
var parser, xmlDoc;
var HTML_captions = "";

// Parse the AJAX response and get the captions.
function getCaption(data) {
  try {

    // Loop the results of the ajax:
    for (var i = 0; i < data.getElementsByTagName("transcript")[0].childNodes.length; i++) {
      HTML_captions += data.getElementsByTagName("transcript")[0].childNodes[i].innerHTML + "<br/>";
    }

    // Preparing captions...
    fillData();

  } catch (err) {
    console.log(err);
    alert('Error at getCaption function - see console form more details.');
  }
}


// Fill the data "captions" in a HTML "div" control.
function fillData() {
  try {
    document.getElementById("demo").innerHTML = HTML_captions;
  } catch (err) {
    console.log(err);
    alert('Error at fillData function - see console form more details.');
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div class="infoVideo">
  <span>These are the captions of the following YouTube video:</span>
  <br/>
  <span>Title: How Turbochargers Work</span>
  <br/>
  <span>URL: https://www.youtube.com/watch?v=zenMEj0cAC4</span>
</div>
<br/>
<div id="demo"><i>Loading captions...</i></div>

Upvotes: 0

Related Questions