みかづきブログ その3

本ブログは更新を終了しました。通算140万ユーザーの方に観覧頂くことができました。長い間、ありがとうございました。

👆

引越し先はこちらです!

YouTube Data API v3 をつかって動画の時間を取得する

JavaScript

(function(win, doc, $) {

  "use strict";

  // KEY は https://console.developers.google.com にて公開APIキーを作成する必要があります
  // ID はYouTubeのVideoIDを使用

  $.ajax({
    type     : "get",
    dataType : "jsonp",
    url      : "https://www.googleapis.com/youtube/v3/videos?id=" + ID + "&key=" + KEY + "&part=contentDetails"
  }).done(function(evt) {
    console.log( _convertDuration(evt.items[0].contentDetails.duration);
  });

  function _convertDuration(durationStr) {
    var str = durationStr,
          h = /^PT([0-9]+)H/.exec(str) ? /^PT([0-9]+)H/.exec(str)[1] : 0,
          m = /([0-9]+)M/.exec(str)    ? /([0-9]+)M/.exec(str)[1]    : 0,
          s = /([0-9]+)S$/.exec(str)   ? /([0-9]+)S$/.exec(str)[1]   : 0;

    return parseInt(s, 10) + parseInt(m, 10) * 60 + parseInt(h , 10) * 60 * 60;
  }

})(this, document, $);

こちらのソースで動画の時間をコンソールに出力することができるはずです。