示例#1
0
  /*
   * Prints out all SearchResults in the Iterator. Each printed line includes title, 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();

      // Double checks the kind is video.
      if (rId.getKind().equals("youtube#video"))
        //     Thumbnail thumbnail = singleVideo.getSnippet().getThumbnails().get("default");

        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");

      // download it
      String link =
          "http://youtubeinmp3.com/fetch/?video=https://www.youtube.com/watch?v="
              + rId.getVideoId();
      System.out.println("to download: " + link);
      WebDownload wd = new WebDownload();
      try {
        wd.downloadMp3FromYoutube("download2.mp3", link);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
示例#2
0
  /**
   * Initializes YouTube object to search for videos on YouTube (Youtube.Search.List). The program
   * then prints the names and thumbnails of each of the videos (only first 50 videos).
   */
  public String videoIdFromQueryTerm(String queryTerm) {
    // Read the developer key from youtube.properties
    String videoId = null;
    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 {
      /*
       * The YouTube object is used to make all API requests. The last argument is required, but
       * because 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(
                  HTTP_TRANSPORT,
                  JSON_FACTORY,
                  new HttpRequestInitializer() {
                    public void initialize(HttpRequest request) throws IOException {}
                  })
              .setApplicationName("youtube-cmdline-search-sample")
              .build();

      // Get query term from user.
      // String queryTerm = getInputQuery();

      YouTube.Search.List search = youtube.search().list("id,snippet");
      /*
       * It is important to set your developer key from the Google Developer Console for
       * non-authenticated requests (found under the API Access tab at this link:
       * code.google.com/apis/). This is good practice and increased your quota.
       */
      String apiKey = "AIzaSyB--WhmXYTrUlitFPWtiPZu8V1w_iPRCbw";
      search.setKey(apiKey);
      search.setQ(queryTerm);
      /*
       * We are only searching for videos (not playlists or channels). If we were searching for
       * more, we would add them as a string like this: "video,playlist,channel".
       */
      search.setType("video");
      /*
       * This method reduces the info returned to only the fields we need and makes calls more
       * efficient.
       */
      search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
      search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
      SearchListResponse searchResponse = search.execute();

      List<SearchResult> searchResultList = searchResponse.getItems();

      SearchResult searchResult = searchResultList.get(0);
      ResourceId rId = searchResult.getId();
      videoId = rId.getVideoId();
      //            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();
    }
    return videoId;
  }