0

Es posible obtener los datos de un vídeo de YouTube? tengo una lista de vídeos de las cuales obtengo la imagen pero necesito el nombre y la descripción, para obtener la imagen uso lo siguiente:

Glide.with(context)
            .load("https://i.ytimg.com/vi/"+ids.get(position)+"/default.jpg")
            .override(300, 200)
            .into(imIcono);

Es posible obtener los otros datos?

He intentado con el siguiente metodo:

private void getVideoInfo() {
    final String packageName = getPackageName();
    String keyYouTubeVideo = "Z26BvHOD_sg";
    String url = "https://www.googleapis.com/youtube/v3/videos?part=id%2C+snippet&id=" + keyYouTubeVideo + "&key=" + API_KEY;
    RequestQueue cola = Volley.newRequestQueue(getApplicationContext());
    cola.getCache().clear();
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray jsonArray = jsonObject.getJSONArray("items");

                        JSONObject object = jsonArray.getJSONObject(0);
                        JSONObject snippet = object.getJSONObject("snippet");

                        String title = snippet.getString("title");


                        Log.d("stuff: ", "" + title);

                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(getApplicationContext(), "Error1!!Por favor contacta al administrador" + e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }

            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplicationContext(), String.valueOf(error), Toast.LENGTH_LONG).show();

        }
    }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json; charset=utf-8");
            headers.put("X-Android-Package", packageName);
            return headers;
        }
    };
    cola.add(stringRequest);


}

Pero obtengo el error:

E/Volley: [358] BasicNetwork.performRequest: Unexpected response code 403 for https://www.googleapis.com/youtube/v3/videos?part=id%2C+snippet&id=Z26BvHOD_sg&key=asdasdasdfasdfasdf

(La API_KEY solo es ejemplo, en el error me muestra la real)

2 respuestas 2

2

Esto lo puedes realizar mediante la Youtube API V3

https://developers.google.com/youtube/v3/docs/videos?hl=es-419

habilita la Youtube API V3 desde la consola

introducir la descripción de la imagen aquí

y obtén el API Key

introducir la descripción de la imagen aquí

Ahora para obtener los datos realiza una petición GET a este url realizando la configuración necesaria:

https://www.googleapis.com/youtube/v3/videos?part=id%2C+snippet&id={YOUTUBE VIDEO ID}&key={API KEY}

de esta forma obtendrás una respuesta con información relacionada al video:

{
  "kind": "youtube#video",
  "etag": etag,
  "id": string,
  "snippet": {
    "publishedAt": datetime,
    "channelId": string,
    "title": string,
    "description": string,
    "thumbnails": {
      (key): {
        "url": string,
        "width": unsigned integer,
        "height": unsigned integer
      }
    },
    "channelTitle": string,
    "tags": [
      string
    ],
    "categoryId": string
  },
  "contentDetails": {
    "duration": string,
    "dimension": string,
    "definition": string,
    "caption": string,
    "licensedContent": boolean,
    "regionRestriction": {
      "allowed": [
        string
      ],
      "blocked": [
        string
      ]
    },
    "contentRating": {
      "mpaaRating": string,
      "tvpgRating": string,
      "bbfcRating": string,
      "chvrsRating": string,
      "eirinRating": string,
      "cbfcRating": string,
      "fmocRating": string,
      "icaaRating": string,
      "acbRating": string,
      "oflcRating": string,
      "fskRating": string,
      "kmrbRating": string,
      "djctqRating": string,
      "russiaRating": string,
      "rtcRating": string,
      "ytRating": string
    }
  },
  "status": {
    "uploadStatus": string,
    "failureReason": string,
    "rejectionReason": string,
    "privacyStatus": string,
    "license": string,
    "embeddable": boolean,
    "publicStatsViewable": boolean
  },
  "statistics": {
    "viewCount": unsigned long,
    "likeCount": unsigned long,
    "dislikeCount": unsigned long,
    "favoriteCount": unsigned long,
    "commentCount": unsigned long
  },
  "player": {
    "embedHtml": string
  },
  "topicDetails": {
    "topicIds": [
      string
    ],
    "relevantTopicIds": [
      string
    ]
  },
  "recordingDetails": {
    "locationDescription": string,
    "location": {
      "latitude": double,
      "longitude": double,
      "altitude": double
    },
    "recordingDate": datetime
  },
  "fileDetails": {
    "fileName": string,
    "fileSize": unsigned long,
    "fileType": string,
    "container": string,
    "videoStreams": [
      {
        "widthPixels": unsigned integer,
        "heightPixels": unsigned integer,
        "frameRateFps": double,
        "aspectRatio": double,
        "codec": string,
        "bitrateBps": unsigned long,
        "rotation": string,
        "vendor": string
      }
    ],
    "audioStreams": [
      {
        "channelCount": unsigned integer,
        "codec": string,
        "bitrateBps": unsigned long,
        "vendor": string
      }
    ],
    "durationMs": unsigned long,
    "bitrateBps": unsigned long,
    "recordingLocation": {
      "latitude": double,
      "longitude": double,
      "altitude": double
    },
    "creationTime": string
  },
  "processingDetails": {
    "processingStatus": string,
    "processingProgress": {
      "partsTotal": unsigned long,
      "partsProcessed": unsigned long,
      "timeLeftMs": unsigned long
    },
    "processingFailureReason": string,
    "fileDetailsAvailability": string,
    "processingIssuesAvailability": string,
    "tagSuggestionsAvailability": string,
    "editorSuggestionsAvailability": string,
    "thumbnailsAvailability": string
  },
  "suggestions": {
    "processingErrors": [
      string
    ],
    "processingWarnings": [
      string
    ],
    "processingHints": [
      string
    ],
    "tagSuggestions": [
      {
        "tag": string,
        "categoryRestricts": [
          string
        ]
      }
    ],
    "editorSuggestions": [
      string
    ]
  }
}
2
1

Podes usar la API de Youtube, necesitas una key para usarla, la podes probar desde esta web, el método que usarías para consultar sería list y como parámetros le podrías pasar part=snippet y en id podes pasar 1 o varios id de videos

Este sería un response de ejemplo con los parámetros que mencioné

{
 "kind": "youtube#videoListResponse",
 "etag": "\"XpPGQXPnxQJhLgs6enD_n8JR4Qk/sYjxalURGWogr5bvKF1saDIoe2s\"",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 1
 },
 "items": [
  {
   "kind": "youtube#video",
   "etag": "\"XpPGQXPnxQJhLgs6enD_n8JR4Qk/X0X7FBoC3LNGN9nwTXJaTKbZOjg\"",
   "id": "d0ODT3feNw4",
   "snippet": {
    "publishedAt": "2017-09-23T00:43:15.000Z",
    "channelId": "UCu4BN1_BtyepZ3hsCPfoDSw",
    "title": "Stack Overflow Video",
    "description": "Stack Overflow is passionate about creating a place for developers to engage and enable one another to drive transformative change in society, and supporting knowledge sharing and use of AI on the Stack Overflow platform will bring more opportunities for developers to do so. Learn how Stack Overflow and Microsoft AI can be used by every developer to provide breakthrough AI innovation using the technologies that you love, making you productive from day 1.  Powered by the robust capabilities of Azure, the Microsoft AI platform allows developers the openness and flexibility to choose the technology and deep learning framework suited for their scenario and skills.",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/d0ODT3feNw4/default.jpg",
      "width": 120,
      "height": 90
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/d0ODT3feNw4/mqdefault.jpg",
      "width": 320,
      "height": 180
     },
     "high": {
      "url": "https://i.ytimg.com/vi/d0ODT3feNw4/hqdefault.jpg",
      "width": 480,
      "height": 360
     },
     "standard": {
      "url": "https://i.ytimg.com/vi/d0ODT3feNw4/sddefault.jpg",
      "width": 640,
      "height": 480
     },
     "maxres": {
      "url": "https://i.ytimg.com/vi/d0ODT3feNw4/maxresdefault.jpg",
      "width": 1280,
      "height": 720
     }
    },
    "channelTitle": "Microsoft Customer Stories",
    "tags": [
     "Azure",
     "Azure Machine",
     "Bot Service",
     "Cognitive Services"
    ],
    "categoryId": "28",
    "liveBroadcastContent": "none",
    "localized": {
     "title": "Stack Overflow Video",
     "description": "Stack Overflow is passionate about creating a place for developers to engage and enable one another to drive transformative change in society, and supporting knowledge sharing and use of AI on the Stack Overflow platform will bring more opportunities for developers to do so. Learn how Stack Overflow and Microsoft AI can be used by every developer to provide breakthrough AI innovation using the technologies that you love, making you productive from day 1.  Powered by the robust capabilities of Azure, the Microsoft AI platform allows developers the openness and flexibility to choose the technology and deep learning framework suited for their scenario and skills."
    },
    "defaultAudioLanguage": "en-US"
   }
  }
 ]
}

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.