自己開發的在線視頻下載工具,基於Java多線程
比如這個在線視頻:
我們可以正常播放,但是找不到下載按鈕。
打開Chrome開發者工具,在Network標簽頁裏能看到很多網絡傳輸請求:
隨便看一個請求的響應,發現類型為video,大小為500多k。因此,這個在線視頻被拆分成了若幹500多k的小片段,然後通過瀏覽器下載到本地進行播放。
這個片段的url:
http://d2vvqvds83fsd.cloudfront.net/vin02/vsmedia/_definst_/smil:event/18/36/06/3/rt/1/resources/180919_PID_Intelligent_Enterprise_Gruenewald_720p-5F92.smil/media_b433000_10.ts
那麽這個片段一共有多少個片段呢?在所有片段開始下載之前,有這樣一個請求:chunklist即是視頻片段的清單。
通過這個清單我們知道這個視頻一共分為55個片段,序號從0開始。
了解了原理,我們就可以開始編程了。
1. 首先實現視頻片段的下載邏輯,新建一個類,實現Runnable接口。
2. 使用JDK自帶的多線程庫 ExecutorService多線程下載這些片段。ExecutorService實際是一個線程池。第15行可以指定線程池裏工作線程(Working thread)的個數。
private void download(){ URL task = null; String path = DownloadLauncher.LOCALPATH + this.mIndex + DownloadLauncher.POSTFIX; String url = this.mTask; try { task = new URL(url); DataInputStream dataInputStream = new DataInputStream(task.openStream()); FileOutputStream fileOutputStream = new FileOutputStream(new File(path)); ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length; while ((length = dataInputStream.read(buffer)) > 0) { output.write(buffer, 0, length); } fileOutputStream.write(output.toByteArray()); dataInputStream.close(); fileOutputStream.close(); System.out.println("File: " + this.mIndex + " downloaded ok"); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
下載完成後,能在Eclipse的console控制臺看到這些輸出:
下載成功的視頻片段:
3. Merger負責把這些片段合並成一個大文件。
private static void run() throws IOException{ FileInputStream in = null; String destFile = DownloadLauncher.LOCALPATH + DownloadLauncher.MERGED; FileOutputStream out = new FileOutputStream(destFile,true); for( int i = 0; i <= DownloadLauncher.LAST; i++){ byte[] buf = new byte[1024]; int len = 0; String sourceFile = DownloadLauncher.LOCALPATH + i + DownloadLauncher.POSTFIX; in = new FileInputStream(sourceFile); while( (len = in.read(buf)) != -1 ){ out.write(buf,0,len); } } out.close(); } public static void main(String[] args) { try { run(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Merged ok!"); }
完整的代碼在我的github上:
https://github.com/i042416/JavaTwoPlusTwoEquals5/tree/master/src/flick
要獲取更多Jerry的原創文章,請關註公眾號"汪子熙":
自己開發的在線視頻下載工具,基於Java多線程