2015-10-21 2 views
1

Я пытаюсь выполнить поиск youtube видео на основе заданного ключевого слова. Чтобы я мог перечислить все найденное видео для отображения в списке с миниатюрами видео. Я не нахожу способ сделать это. После поиска я нашел это https://developers.google.com/youtube/v3/docs/videos/list#examples.Как искать видео youtube в Android по определенному ключевому слову

Могу ли я использовать сохранение для моего приложения для Android? Или как я могу искать в приложении Android?

ответ

3

Вы можете использовать примеры кода API Youtube в своем приложении на следующих условиях:
1. Ваше приложение - бесплатное приложение.
2. Если ваше приложение монетизировано (оплачивается, рекламируется и/или в покупках приложений), ваше приложение должно содержать больше контента и функций, чем только функцию поиска Youtube.

Все подробности здесь: https://developers.google.com/youtube/creating_monetizable_applications

Это, как говорится, вы можете в полной мере использовать образцы кода из Youtube API. Я сделал это сам, чтобы создать приложение для Android, чтобы помочь людям найти все мои любимые кошки видео (бесстыдной продвижение): Cat Roulette

Во всяком случае, вот конкретный пример кода Java для поиска Youtube видео: https://developers.google.com/youtube/v3/code_samples/java#search_by_keyword

/* 
* Copyright (c) 2012 Google Inc. 
* 
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 
* in compliance with the License. You may obtain a copy of the License at 
* 
* http://www.apache.org/licenses/LICENSE-2.0 
* 
* Unless required by applicable law or agreed to in writing, software distributed under the License 
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 
* or implied. See the License for the specific language governing permissions and limitations under 
* the License. 
*/ 

package com.google.api.services.samples.youtube.cmdline.data; 

import com.google.api.client.googleapis.json.GoogleJsonResponseException; 
import com.google.api.client.http.HttpRequest; 
import com.google.api.client.http.HttpRequestInitializer; 
import com.google.api.client.http.HttpTransport; 
import com.google.api.client.http.javanet.NetHttpTransport; 
import com.google.api.client.json.JsonFactory; 
import com.google.api.client.json.jackson2.JacksonFactory; 
import com.google.api.services.samples.youtube.cmdline.Auth; 
import com.google.api.services.youtube.YouTube; 
import com.google.api.services.youtube.model.ResourceId; 
import com.google.api.services.youtube.model.SearchListResponse; 
import com.google.api.services.youtube.model.SearchResult; 
import com.google.api.services.youtube.model.Thumbnail; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.util.Iterator; 
import java.util.List; 
import java.util.Properties; 

/** 
* Print a list of videos matching a search term. 
* 
* @author Jeremy Walker 
*/ 
public class Search { 

    /** 
    * Define a global variable that identifies the name of a file that 
    * contains the developer's API key. 
    */ 
    private static final String PROPERTIES_FILENAME = "youtube.properties"; 

    private static final long NUMBER_OF_VIDEOS_RETURNED = 25; 

    /** 
    * Define a global instance of a Youtube object, which will be used 
    * to make YouTube Data API requests. 
    */ 
    private static YouTube youtube; 

    /** 
    * Initialize a YouTube object to search for videos on YouTube. Then 
    * display the name and thumbnail image of each video in the result set. 
    * 
    * @param args command line args. 
    */ 
    public static void main(String[] args) { 
     // Read the developer key from the properties file. 
     Properties properties = new Properties(); 
     try { 
      InputStream in = Search.class.getResourceAsStream("/" + PROPERTIES_FILENAME); 
      properties.load(in); 

     } catch (IOException e) { 
      System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause() 
        + " : " + e.getMessage()); 
      System.exit(1); 
     } 

     try { 
      // This object is used to make YouTube Data API requests. The last 
      // argument is required, but since we don't need anything 
      // initialized when the HttpRequest is initialized, we override 
      // the interface and provide a no-op function. 
      youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() { 
       public void initialize(HttpRequest request) throws IOException { 
       } 
      }).setApplicationName("youtube-cmdline-search-sample").build(); 

      // Prompt the user to enter a query term. 
      String queryTerm = getInputQuery(); 

      // Define the API request for retrieving search results. 
      YouTube.Search.List search = youtube.search().list("id,snippet"); 

      // Set your developer key from the Google Developers Console for 
      // non-authenticated requests. See: 
      // https://console.developers.google.com/ 
      String apiKey = properties.getProperty("youtube.apikey"); 
      search.setKey(apiKey); 
      search.setQ(queryTerm); 

      // Restrict the search results to only include videos. See: 
      // https://developers.google.com/youtube/v3/docs/search/list#type 
      search.setType("video"); 

      // To increase efficiency, only retrieve the fields that the 
      // application uses. 
      search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)"); 
      search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED); 

      // Call the API and print results. 
      SearchListResponse searchResponse = search.execute(); 
      List<SearchResult> searchResultList = searchResponse.getItems(); 
      if (searchResultList != null) { 
       prettyPrint(searchResultList.iterator(), queryTerm); 
      } 
     } catch (GoogleJsonResponseException e) { 
      System.err.println("There was a service error: " + e.getDetails().getCode() + " : " 
        + e.getDetails().getMessage()); 
     } catch (IOException e) { 
      System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage()); 
     } catch (Throwable t) { 
      t.printStackTrace(); 
     } 
    } 

    /* 
    * Prompt the user to enter a query term and return the user-specified term. 
    */ 
    private static String getInputQuery() throws IOException { 

     String inputQuery = ""; 

     System.out.print("Please enter a search term: "); 
     BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in)); 
     inputQuery = bReader.readLine(); 

     if (inputQuery.length() < 1) { 
      // Use the string "YouTube Developers Live" as a default. 
      inputQuery = "YouTube Developers Live"; 
     } 
     return inputQuery; 
    } 

    /* 
    * Prints out all results in the Iterator. For each result, print the 
    * title, video ID, and thumbnail. 
    * 
    * @param iteratorSearchResults Iterator of SearchResults to print 
    * 
    * @param query Search query (String) 
    */ 
    private static void prettyPrint(Iterator<SearchResult> iteratorSearchResults, String query) { 

     System.out.println("\n============================================================="); 
     System.out.println(
       " First " + NUMBER_OF_VIDEOS_RETURNED + " videos for search on \"" + query + "\"."); 
     System.out.println("=============================================================\n"); 

     if (!iteratorSearchResults.hasNext()) { 
      System.out.println(" There aren't any results for your query."); 
     } 

     while (iteratorSearchResults.hasNext()) { 

      SearchResult singleVideo = iteratorSearchResults.next(); 
      ResourceId rId = singleVideo.getId(); 

      // Confirm that the result represents a video. Otherwise, the 
      // item will not contain a video ID. 
      if (rId.getKind().equals("youtube#video")) { 
       Thumbnail thumbnail = singleVideo.getSnippet().getThumbnails().getDefault(); 

       System.out.println(" Video Id" + rId.getVideoId()); 
       System.out.println(" Title: " + singleVideo.getSnippet().getTitle()); 
       System.out.println(" Thumbnail: " + thumbnail.getUrl()); 
       System.out.println("\n-------------------------------------------------------------\n"); 
      } 
     } 
    } 
} 


FYI вы должны также получить ключ API Youtube, как описано здесь:
https://developers.google.com/youtube/registering_an_application?hl=en

+0

Спасибо за ответ. Я нашел этот код раньше. Но он ничего не упоминал об Android. Поэтому я догадался, что это может быть только для JSE. У меня нет машины для разработки. Я попробую завтра. Как вы уже сделали приложение. Я считаю, что это определенно сработает для меня. В случае возникновения какой-либо проблемы я снова буду вас беспокоить;) – masiboo

+0

FYI. Я использовал код, который я предоставил, конечно, Java (не Javascript). Java является предпочтительным и наиболее часто используемым языком для разработки Android. – joshgoldeneagle

+0

Спасибо большое! Он отлично работал. благодаря – masiboo

Смежные вопросы