Java 下载 HLS (m3u8) 视频

下载索引文件

public String getIndexFile() throws Exception{
    URL url = new URL(originUrlpath);
    //下载资源
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(),"UTF-8"));

    String content = "" ;
    String line;
    while ((line = in.readLine()) != null) {
        content += line + "\n";
    }
    in.close();

    return content;
}

解析索引文件

public List analysisIndex(String content) throws Exception{
    Pattern pattern = Pattern.compile(".*ts");
    Matcher ma = pattern.matcher(content);

    List list = new ArrayList();

    while(ma.find()){
        list.add(ma.group());
    }

    return list;
}

下载视频片段

同步下载

public HashMap downLoadIndexFile(List urlList){
    HashMap keyFileMap = new HashMap<>();

    for(int i =0;i

多线程下载

public void downLoadIndexFileAsync(List urlList, HashMap keyFileMap) throws Exception{
    int downloadForEveryThread = (urlList.size() + threadQuantity - 1)/threadQuantity;
    if(downloadForEveryThread == 0) downloadForEveryThread = urlList.size();

    for(int i=0; i= urlList.size())
            endIndex = urlList.size() - 1;

        new DownloadThread(urlList, startIndex, endIndex, keyFileMap).start();
    }
}

class DownloadThread extends Thread{
    private List urlList;
    private int startIndex;
    private int endIndex;
    private HashMap keyFileMap;

    public DownloadThread(List urlList, int startIndex, int endIndex, HashMap keyFileMap){
        this.urlList = urlList;
        this.startIndex = startIndex;
        this.endIndex = endIndex;
        this.keyFileMap = keyFileMap;
    }
    @Override
    public void run(){
        for(int i=startIndex;i<=endIndex;i++){
            String subUrlPath = urlList.get(i);
            String fileOutPath = folderPath + File.separator + i + ".ts";
            keyFileMap.put(i, fileOutPath);
            String message = "%s: 线程 " + (startIndex/(endIndex - startIndex) + 1)
                    + ", "+ (i + 1) +"/" + urlList.size() +", 合计: %d";
            try{
                downloadNet(preUrlPath + subUrlPath, fileOutPath);

                System.out.println(String.format(message, "成功", keyFileMap.size()));
            }catch (Exception e){
                System.err.println(String.format(message, "失败", keyFileMap.size()));
            }
        }
    }
}

视频片段合成

public String composeFile(HashMap keyFileMap) throws Exception{

    if(keyFileMap.isEmpty()) return null;

    String fileOutPath = rootPath + File.separator + fileName;
    FileOutputStream fileOutputStream = new FileOutputStream(new File(fileOutPath));
    byte[] bytes = new byte[1024];
    int length = 0;
    for(int i=0; i

开源地址:hlsdownloader

参考:M3U8在线视频文件下载合成MP4视频

转载于:https://www.cnblogs.com/victorbu/p/10347663.html

你可能感兴趣的:(Java 下载 HLS (m3u8) 视频)