Program Resource

開発者向け各種コード、アルゴリズム、リソース情報ライブラリ もしくはねふぁの覚え書き

ニコニコ動画はxml形式で動画の情報を取得する事が出来る。この情報を利用して、Youtubeの動画URLからタイトル、再生時間、サムネイルのBitmapを取得するサンプルコードを紹介する。

動画のタイトル及び再生時間を文字列で返すコード。

public String Nico_Fetchinfo(Context context,String url,int timeout){
	String infourl="";
	if (!url.toLowerCase().contains("nicovideo"))
		return null;

	//sm#の場合とsmなしで#の場合がある
	Pattern p = Pattern.compile(".+/sm(\\d+)");
	Matcher m = p.matcher(url);
	if (m.find()) {
		infourl = "http://ext.nicovideo.jp/api/getthumbinfo/sm"+m.group(1);
	}else{
		p = Pattern.compile(".+/(\\d+)");
		m = p.matcher(url);
		if (m.find()) {
			infourl = "http://ext.nicovideo.jp/api/getthumbinfo/"+m.group(1);
		}else
			return null;
		}
	}

	int responseCode = 0;
	int duration=0;
	String sduration="";
	String title="";
	String movietitle = new String();

	try {
		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();

			//情報から必要なデータを取り出す
			Pattern dp = Pattern.compile("<length>(.*?)</");
			Matcher dm = dp.matcher(html);
			if (dm.find()) {
				try {
					sduration = dm.group(1);
				}catch(Exception e){duration=0;}
			}

			Pattern tp = Pattern.compile("<title>(.*?)</");
			Matcher tm = tp.matcher(html);
			if (tm.find()) {
				title = tm.group(1);
				if (title.length()>0){
					movietitle = title+" ("+sduration+")";
					movietitle = movietitle.replace("&amp;","&");
					movietitle = movietitle.replace("&gt;","<");
					movietitle = movietitle.replace("&lt;",">");
					movietitle = movietitle.replace("&quot;","\"");
					return movietitle;
				}
			}
		} else if (responseCode == 403){ //forbidden
			movietitle = "閲覧規制";
			return movietitle;
		}
	} catch (ClientProtocolException e) {
	} catch (IOException e) {
	}
	return null;
}

サムネイル画像の取得コード。

public String Nico_FetchThumurlinfo(Context context,String url,int timeout){
	String infourl="";
	if (!url.toLowerCase().contains("nicovideo"))
		return null;

	Pattern p = Pattern.compile(".+/sm(\\d+)");
	Matcher m = p.matcher(url);
	if (m.find()) {
		infourl = "http://ext.nicovideo.jp/api/getthumbinfo/sm"+m.group(1);
	}else{
		p = Pattern.compile(".+/(\\d+)");
		m = p.matcher(url);
		if (m.find()) {
			infourl = "http://ext.nicovideo.jp/api/getthumbinfo/"+m.group(1);
		}else
			return null;
	}

	int responseCode = 0;
	String thumurl = new String();

	try {
		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();

			Pattern dp = Pattern.compile("<thumbnail_url>(.*?)</");
			Matcher dm = dp.matcher(html);
			if (dm.find()) {
				try {
					thumurl = dm.group(1);
					return thumurl;
				}catch(Exception e){}
			}
		}
	} catch (ClientProtocolException e) {
	} catch (IOException e) {
	}
	return null;
}

public Bitmap Nico_Fetchthum(Context context,String url){
	String vid="";
	String turl="";
	if (!url.toLowerCase().contains("nicovideo"))
		return null;

	Pattern p = Pattern.compile(".+/sm(\\d+)");
	Matcher m = p.matcher(url);
	if (m.find()) {
		vid = m.group(1);
	}else{
		p = Pattern.compile(".+/(\\d+)");
		m = p.matcher(url);
		if (m.find()) {
			vid = m.group(1);
			turl = "tobefetched";
		}else
			return null;
		}
	}
	if (vid.length()<2)
		return null;

	try {
		URL imageUrl;
		int thindex;
		//サムネルURL成形、ビデオ情報からサムネイルURL取得する方法も入れた理由は忘れた
		//数字のみのURLの場合サムネイルの場所が違っていたからだったかも
		thindex = (Integer.parseInt(vid))%4+1;
		if (turl.equals(""))
			imageUrl = new URL("http://tn-skr"+thindex+".smilevideo.jp/smile?i="+vid);
		else{
			turl = VGmark_FetchThumurlinfo(context,url,3000);
			if (turl.equals(""))
				imageUrl = new URL("http://tn-skr"+thindex+".smilevideo.jp/smile?i="+vid);
			else
				imageUrl = new URL(turl);
			}
		}

		InputStream imageIs;
		imageIs = imageUrl.openStream();

		File saveDir;
		String filepath;
		//キャッシュ用にSDカード内ファイルに保存していますが、必要に応じ別の場所かメモリから直接に変えること
		saveDir = new File(Environment.getExternalStorageDirectory().getAbsoluteFile()+"/mymato/videothum/");
		filepath = Environment.getExternalStorageDirectory().getAbsoluteFile()+"/mymato/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;
	}
}

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です


*