自己开发的在线视频下载工具,基于Java多线程
比如這個(gè)在線視頻:
我們可以正常播放,但是找不到下載按鈕。
打開Chrome開發(fā)者工具,在Network標(biāo)簽頁里能看到很多網(wǎng)絡(luò)傳輸請(qǐng)求:
隨便看一個(gè)請(qǐng)求的響應(yīng),發(fā)現(xiàn)類型為video,大小為500多k。因此,這個(gè)在線視頻被拆分成了若干500多k的小片段,然后通過瀏覽器下載到本地進(jìn)行播放。
這個(gè)片段的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
那么這個(gè)片段一共有多少個(gè)片段呢?在所有片段開始下載之前,有這樣一個(gè)請(qǐng)求:chunklist即是視頻片段的清單。
通過這個(gè)清單我們知道這個(gè)視頻一共分為55個(gè)片段,序號(hào)從0開始。
了解了原理,我們就可以開始編程了。
1. 首先實(shí)現(xiàn)視頻片段的下載邏輯,新建一個(gè)類,實(shí)現(xiàn)Runnable接口。
2. 使用JDK自帶的多線程庫 ExecutorService多線程下載這些片段。ExecutorService實(shí)際是一個(gè)線程池。第15行可以指定線程池里工作線程(Working thread)的個(gè)數(shù)。
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控制臺(tái)看到這些輸出:
下載成功的視頻片段:
3. Merger負(fù)責(zé)把這些片段合并成一個(gè)大文件。
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的原創(chuàng)文章,請(qǐng)關(guān)注公眾號(hào)"汪子熙":
總結(jié)
以上是生活随笔為你收集整理的自己开发的在线视频下载工具,基于Java多线程的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java如何计算hashcode值
- 下一篇: java美元兑换,(Java实现) 美元