Youtubeの動画はxml形式で動画の情報を取得する事が出来る。この情報を利用して、Youtubeの動画URLからタイトル、再生時間、サムネイルのBitmapを取得するサンプルコードを紹介する。
動画のタイトル及び再生時間を文字列で返すコード。
public String Youtube_Fetchinfo(Context context,String url,int timeout){ String infourl=""; if (!url.toLowerCase().contains("youtube")) return null; //get video ID Pattern p = Pattern.compile(".+v=([^&\"]*)"); Matcher m = p.matcher(url); if (m.find()) { infourl = "http://gdata.youtube.com/feeds/api/videos/"+m.group(1); }else{ return null; } int responseCode = 0; int duration=0; String sduration=""; String title=""; String movietitle = new String(); try { //Get video information String defaultUA = "Mozilla/5.0 (Linux; U; Android 2.1; en-us) AppleWebKit/522+ (KHTML, like Gecko) Safari/419.3"; HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(infourl); HttpResponse httpResponse = null; httpClient.getParams().setParameter("http.connection.timeout", new Integer(timeout)); HttpParams params1 = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params1, timeout); HttpConnectionParams.setSoTimeout(params1, timeout); params1.setParameter(HttpProtocolParams.USER_AGENT, defaultUA); httpResponse = httpClient.execute(httpGet); responseCode = httpResponse.getStatusLine().getStatusCode(); if (responseCode == HttpStatus.SC_OK) { InputStream istream = httpResponse.getEntity().getContent(); InputStreamReader reader = new InputStreamReader(istream); BufferedReader objBuf = new BufferedReader(reader); StringBuilder builder = new StringBuilder(); String sLine; while((sLine = objBuf.readLine()) != null){ builder.append(sLine);} String html = builder.toString(); istream.close(); //find duration info Pattern dp = Pattern.compile("seconds='(\\d+?)'"); Matcher dm = dp.matcher(html); if (dm.find()) { try { duration = Integer.parseInt(dm.group(1)); }catch(Exception e){duration=0;} } //find video title Pattern tp = Pattern.compile("<title.*?>(.*?)</"); Matcher tm = tp.matcher(html); if (tm.find()) { title = tm.group(1); if (title.length()>0){ if (duration > 60) movietitle = title+" ("+(duration/60)+"min)"; else movietitle = title+" ("+duration+"sec)"; movietitle = movietitle.replace("&","&"); movietitle = movietitle.replace(">","<"); movietitle = movietitle.replace("<",">"); movietitle = movietitle.replace(""","\""); return movietitle; } } } else if (responseCode == 403){ //forbidden movietitle = "forbidden"; return movietitle; } } catch (ClientProtocolException e) { } catch (IOException e) { return null; }
サムネイル画像の取得コード。
public Bitmap VGinfo_Fetchthum(Context context,String url){ String vid=""; String turl=""; if (!url.toLowerCase().contains("youtube")) return null; Pattern p = Pattern.compile(".+v=([^&\"]*)"); Matcher m = p.matcher(url); if (m.find()) { vid = m.group(1); }else return null; if (vid.length()<2) return null; try { URL imageUrl; imageUrl = new URL("http://i.ytimg.com/vi/"+vid+"/1.jpg"); InputStream imageIs; imageIs = imageUrl.openStream(); //saving image to SD card (to be used for caching), change location or return data directly as needed File saveDir; String filepath; saveDir = new File(Environment.getExternalStorageDirectory().getAbsoluteFile()+"/simpleweb/videothum/"); filepath = Environment.getExternalStorageDirectory().getAbsoluteFile()+"/simpleweb/videothum/"+vid+".jpg"; if(!saveDir.exists()) { if (!saveDir.mkdirs()) { //can't save to file, load to memory Bitmap image = BitmapFactory.decodeStream(imageIs); return image; } } File file = new File(filepath); BufferedInputStream bufferedInputStream = new BufferedInputStream(imageIs, 10240); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file, false), 10240); byte buffer[] = new byte[10240]; int size = 0; while(-1 != (size = bufferedInputStream.read(buffer))) { bufferedOutputStream.write(buffer, 0, size); } bufferedOutputStream.flush(); bufferedOutputStream.close(); bufferedInputStream.close(); Bitmap bmSource = BitmapFactory.decodeFile(filepath); return bmSource; } catch (MalformedURLException e) { return null; } catch (IOException e) { return null; } }
This post is also available in: 英語
便利なコード,ありがとうございます。
利用させていただきます。
しかし,11行目にシンタックスエラーがある気がするので,訂正されてはどうでしょうか?
{が抜けていますね。指摘ありがとうございます。
修正しておきました。