Java獲取m3u8視訊時長

一枚菜鳥程式設計師發表於2020-12-29

步驟

1、獲取到m3u8的地址;
2、通過URL請求獲取到m3u8的標頭檔案資訊;
3、讀取標頭檔案中每一個分片的時間求和可得出時長。

m3u8標頭檔案文字如下

#EXTM3U
#EXT-X-VERSION:3
#EXT-X-ALLOW-CACHE:YES
#EXT-X-TARGETDURATION:10
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-KEY:METHOD=AES-128,URI=“https://api.izhangchu.com/?methodName=VideoDecrypt&Ciphertext=NTYyYWYyMzEtYzVhOC00YzRjLWI4ODUtYjQzY2RkOWExYzZlTDJ1WW5za0RXM0ZVR2liT2tNU3lsWUVMWVJXY2NlbStBQUFBQUFBQUFBQXlucFFCaU5RN24zRDR0NnVtTG5nR0k4bTd0VmtwSW9QWGZRMEJxZTdOUEJDdmlHd1pZZDlz”
#EXTINF:10.000000,
30f52035991ba776dbceeaa6a12907ae-ld-encrypt-stream-00001.ts
#EXTINF:10.000000,
30f52035991ba776dbceeaa6a12907ae-ld-encrypt-stream-00002.ts
#EXTINF:9.000000,
30f52035991ba776dbceeaa6a12907ae-ld-encrypt-stream-00003.ts
#EXT-X-ENDLIST

部分程式碼如下

// An highlighted block
        Long duration = 0L;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        try {
            URL url1 = new URL(url);
            URLConnection connection = url1.openConnection();
            inputStream = connection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(inputStreamReader);
            String str ;
            while (((str = bufferedReader.readLine()) != null)) {
                //按行讀取m3u8標頭檔案
                //#EXTINF:後的內容就是每一個分片的時長,單位為秒
                if (str.contains("#EXTINF:")) {
                    Double doubleDuration  = Double.valueOf(str.substring(8,15));
                    doubleDuration = doubleDuration * 1000;
                    duration += doubleDuration.longValue();
                }
            }
        }

相關文章