Воспроизведение видео, полученных из youtube API v3

Используя Youtube API V3, я могу извлекать миниатюры видео из ленты активности пользователя (используя активности из API).

Я пытаюсь добиться того, чтобы когда пользователь нажимал на видео, видео должно воспроизводиться. Я посмотрел на iframes. однако список действий в API не показывает, как получить URL-адрес для видео, а другой Videos показывает поле player.embedHtml, однако я не понимаю, как интегрировать его в свой код.

    var activityId, nextPageToken, prevPageToken, videoSnippet;

// Once the api loads call a function to get the uploads playlist id.
function handleAPILoaded() {
  requestUserUploadsactivityId();
}

//Retrieve the uploads playlist id.
function requestUserUploadsactivityId() {
  // https://developers.google.com/youtube/v3/docs/channels/list
  var request = gapi.client.youtube.activities.list({
    // mine: '' indicates that we want to retrieve the channel for the authenticated user.
    home: 'true',
    part: 'snippet'
  });
  request.execute(function(response) {
    //structure of content.details
    //https://developers.google.com/youtube/v3/docs/channels#resource
    console.log(response);
    activityId = response.items[0].id;
    requestVideoPlaylist(activityId);
  });
}

// Retrieve a playist of videos.
function requestVideoPlaylist(home, pageToken) {
  $('#video-container').html('');
  var requestOptions = {
    home: 'true',
    part: 'snippet',
    maxResults: 12
  };
  if (pageToken) {
    requestOptions.pageToken = pageToken;
  }
  var request = gapi.client.youtube.activities.list(requestOptions);
  request.execute(function(response) {


    var activityItems = response.result.items;
    if (activityItems) {
      // For each result lets show a thumbnail.
      jQuery.each(activityItems, function(index, item) {
        createDisplayThumbnail(item.snippet);

      });
    } else {
      $('#video-container').html('Sorry you have no activities on your feed');
    }
  });
}


// Create a thumbnail for a video snippet.
function createDisplayThumbnail(videoSnippet) {
  var titleEl = $('<h4>');
  titleEl.addClass('video-title');
  $(titleEl).html(videoSnippet.title);
  var thumbnailUrl = videoSnippet.thumbnails.default.url;
   console.log(videoSnippet);
  var div = $('<div>');
  div.addClass('video-content');
  div.css('backgroundImage', 'url("' + thumbnailUrl + '")');
  div.append(titleEl);
  $('#video-container').append(div);
}

person Dot    schedule 20.06.2013    source источник


Ответы (1)


Список действий включает в себя несколько видов действий:

загрузить, лайкнуть, добавить в избранное, комментарий, подписку, плейлист, рекомендацию, бюллетень, соц.

и только некоторые виды деятельности связаны с видео. Затем вы можете получить videoId из contentDetails только тогда, когда тип действия связан с видео. Вы можете использовать videoId для показа видео.

https://developers.google.com/youtube/v3/docs/activities

У вас есть хороший пример в "YouTube Topic Explorer". В этом приложении вы можете получить информацию о социальных действиях и получить идентификатор видео из таких действий.

https://code.google.com/p/yt-topic-explorer/source/browse/app/scripts/controllers/logged-in.js

$scope.social = function() {
    $rootScope.topicResults = [];
    $rootScope.spinner.spin($('#spinner')[0]);

        youtube({
          method: 'GET',
          service: 'activities',
          params: {
                part: 'id,snippet,contentDetails',
                home: true,
                maxResults: constants.YOUTUBE_API_MAX_RESULTS
          },
          callback: function(response) {
                  if ('items' in response) {
                          $scope.videoIds = [];
                          $scope.personalizedTopics = [];
                          angular.forEach(response.items, function(activity) {
                                if ((activity.snippet.type == constants.SOCIAL_TYPE)&&(activity.contentDetails.social.resourceId.videoId)){
                                        $scope.videoIds.push(activity.contentDetails.social.resourceId.videoId);
                                }
                          });
                  }
                  getTopicsForVideoIds();
          }
        });
  }

и у вас есть пример того, как показать видео:

https://code.google.com/p/yt-topic-explorer/source/browse/app/scripts/controllers/main.js

 function playVideo(container, videoId) {
    var width = container.offsetWidth;
    var height = container.offsetHeight;

    new YT.Player(container, {
      videoId: videoId,
      width: width,
      height: height,
      playerVars: {
        autoplay: 1,
        controls: 2,
        modestbranding: 1,
        rel: 0,
        showInfo: 0
      }
    });
person Matias Molinas    schedule 21.06.2013
comment
! большое спасибо, а есть демо для этого где-нибудь? также что делает метод getTopicsForvideoIds()? это выглядит немного сложно. - person Dot; 22.06.2013