java把m3u8视频转为mp4

java把m3u8视频转为mp4

代码

import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Title: Process
 * @Author cxf
 * @Package com.example.demo.test
 * @Date 2024/7/11 10:29
 * @description: 测试
 */
public class ProcessUtils {

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        List<String> splice = splice();
        if (!splice.isEmpty()) {
            for (String command : splice) {
                int result = ProcessUtils.executeCommand(command);
                if (result == 0) {
                    try {
                        //System.out.println("command "+command);
                        String replace = command.replace("copy /b ", "");
                        String[] split = replace.split(" \\+ ");
                        String string = split[0];
                        String sub = string.substring(0, string.lastIndexOf("\\"));
                        String target = sub.substring(0, sub.lastIndexOf("\\"));
                        File file = new File(target);
                        if (file.exists()) {
                            deleteDirectory(file);
                        }
                        TimeUnit.SECONDS.sleep(3);
                    } catch (Exception e) {

                    }
                } else {
                    System.out.println(command);
                    System.out.println(result);
                }
            }
        }

        long end = System.currentTimeMillis();
        System.out.println("处理完成,耗时:" + ((end - start) / 1000) + "秒");

       /* try {
            TimeUnit.MINUTES.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
    }

    private static List<String> splice() {
        int count = 0;
        int stop = 10;
        // 25个小文件合成一个临时文件
        int batchSize = 30;

        List<String> strList = new ArrayList<>();
        try {
            // ts文件所在目录
            String dirPath = "D:\\movie";
            // MP4存放目录
            String moviePath = "D:\\video\\";
            File file = new File(dirPath);
            if (file.exists()) {// 1.判断文件是否存在
                File[] movieDir = file.listFiles();
                for (File dir : movieDir) {
                    if (count > stop) {
                        break;
                    }
                    File[] tsDir = dir.listFiles();
                    if(tsDir.length > 0){
                        count++;
                        if (dir.isDirectory()) {
                            String tmpDir = dir.getAbsolutePath();
                            File videoPath = new File(tmpDir);
                            File[] files = videoPath.listFiles();
                            List<String> sortList = new ArrayList<String>();
                            for (File file2 : files) {
                                if (file2.isDirectory()) {
                                    String absolutePath = file2.getAbsolutePath();

                                    File videos = new File(absolutePath + "");
                                    File[] ts = videos.listFiles();
                                    int total = ts.length;
                                    if (total > 0) {
                                        for (File t : ts) {
                                            String name = t.getName();
                                            if (!(name.endsWith(".class") || name.endsWith(".bat"))) {
                                                if (name.endsWith("ts")) {
                                                    sortList.add(name);
                                                }
                                            }
                                        }
                                        sortList.sort((o1, o2) -> {
                                            String split1 = o1.split("\\.")[0];
                                            String split2 = o2.split("\\.")[0];
                                            int parseInt1;
                                            int parseInt2;
                                            try {
                                                parseInt1 = Integer.parseInt(split1);
                                                parseInt2 = Integer.parseInt(split2);
                                            } catch (NumberFormatException e) {//如果是非数字,按照原来的顺序
                                                return 0;
                                            }
                                            if (parseInt1 > parseInt2) {
                                                return 1;
                                            } else {
                                                return -1;
                                            }
                                        });
                                        int size = sortList.size();

                                        if (size > batchSize) {
                                            List<String> temList = new ArrayList<>();
                                            String tmp = tmpDir + "\\tmp\\";
                                            File t = new File(tmp);
                                            if (!t.exists()) {
                                                t.mkdir();
                                            } else {
                                                tmp = tmpDir + "\\tmp2\\";
                                                t = new File(tmp);
                                                t.mkdir();
                                            }

                                            for (int s = 0; s < size; s += batchSize) {
                                                int endIndex = Math.min(s + batchSize, size);
                                                List<String> subList = sortList.subList(s, endIndex);
                                                int subListSize = subList.size();
                                                StringBuffer fw = new StringBuffer("copy /b ");
                                                for (int i = 0; i < subListSize; i++) {
                                                    if (i == subListSize - 1) {
                                                        fw.append(absolutePath).append("\\");
                                                        fw.append(subList.get(i));
                                                        break;
                                                    }
                                                    fw.append(absolutePath).append("\\");
                                                    fw.append(subList.get(i)).append(" + ");
                                                }
                                                long timeMillis = System.currentTimeMillis();

                                                fw.append(" ").append(tmp);
                                                fw.append(timeMillis).append(".ts");

                                                String com = fw.toString();
                                                //System.out.println(com);
                                                temList.add(com);
                                                TimeUnit.MILLISECONDS.sleep(500);
                                            }
                                            tmpVideo(temList, absolutePath);
                                        } else {
                                            StringBuffer fw = new StringBuffer("copy /b ");
                                            for (int i = 0; i < size; i++) {
                                                if (i == size - 1) {
                                                    fw.append(absolutePath).append("\\");
                                                    fw.append(sortList.get(i));
                                                    break;
                                                }
                                                fw.append(absolutePath).append("\\");
                                                fw.append(sortList.get(i)).append(" + ");
                                            }
                                            long timeMillis = System.currentTimeMillis();
                                            fw.append(" ").append(moviePath);
                                            fw.append(timeMillis).append(".mp4");
                                            String com = fw.toString();
                                            //System.out.println(com);
                                            strList.add(com);
                                            TimeUnit.MILLISECONDS.sleep(1000);
                                        }
                                    }
                                }
                            }
                        }
                    }else{
                        System.out.println("空文件夹 "+ dir.getAbsolutePath());
                     dir.delete();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strList;
    }

    // 将多个小文件合成临时文件,删除小文件
    private static void tmpVideo(List<String> strList, String path) throws Exception {
        if (!strList.isEmpty()) {
            boolean flag = true;
            int r = 0;
            for (String com : strList) {
                //System.out.println(com);
                int result = ProcessUtils.executeCommand(com);
                r++;
                if (result == 0) {
                    //TimeUnit.MILLISECONDS.sleep(1000);
                } else {
                    flag = false;
                    System.out.println("失败批次:" + com);
                }
            }
            if (flag) {
                deleteDirectory(new File(path));
                System.out.println("删除 " + path + " 成功");
            }

        }
    }


    public static int executeCommand(String command) {
        int exitCode = 1;
        Charset charset = System.getProperty("os.name").toLowerCase().contains("win") ? Charset.forName("GBK") : Charset.defaultCharset();
        String os = System.getProperty("os.name").toLowerCase();
        List<String> commands = new ArrayList<>();

        // 判断操作系统类型,并准备命令
        if (os.contains("win")) {
            // Windows
            commands.add("cmd");
            commands.add("/c");
        } else {
            // Unix/Linux/MacOS
            commands.add("/bin/sh");
            commands.add("-c");
        }

        commands.add(command);

        // 执行命令并获取结果
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(commands);
            Process process = processBuilder.start();

            // 获取输出
            String output = readStream(process.getInputStream(), charset);
            // 等待进程结束
            exitCode = process.waitFor();
            if (exitCode == 0) {
                return exitCode;
            } else {
                String error = readStream(process.getErrorStream(), charset);
                System.out.println("exit code " + exitCode + " and error: " + error);
                throw new IOException("exit code " + exitCode + " and error: " + error + output);
            }
        } catch (IOException | InterruptedException e) {
            Thread.currentThread().interrupt();
            //return "Error: " + e.getMessage();
        }
        return exitCode;
    }

    private static void deleteDirectory(File directory) throws Exception {
        if (directory.exists()) {
            Files.walk(directory.toPath())
                    .sorted((p1, p2) -> -p1.compareTo(p2))
                    .map(Path::toFile)
                    .forEach(File::delete);

            System.out.println("已删除: " + directory.getAbsolutePath());
        }
    }

    private static String readStream(InputStream inputStream, Charset charset) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, charset));
        StringBuilder builder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            builder.append(line);
            builder.append(System.getProperty("line.separator"));
        }
        return builder.toString();
    }

    public static void test(String[] args) throws IOException {
        String property = System.getProperty("user.dir");
        File file = new File(property);// 文件夹
        String runFilePath = property + "/new.bat";
        File runFile = new File(runFilePath);// 生成的可执行文件
        FileWriter fw = null;
        try {
            fw = new FileWriter(runFile);
            fw.append("copy /b ");
            fw.flush();
            if (file.exists()) {// 1.判断文件是否存在
                if (file.isDirectory()) {// 2.判断是否为文件夹
                    File[] listFiles = file.listFiles();
                    List<String> sortList = new ArrayList<String>();
                    for (File file2 : listFiles) {
                        String name = file2.getName();// 获取名字
                        if (!(name.endsWith(".class") || name.endsWith(".bat"))) {
                            sortList.add(name);
                        }
                    }
                    //4.排序
                    sortList.sort((o1, o2) -> {
                        String split1 = o1.split("\\.")[0];
                        String split2 = o2.split("\\.")[0];
                        int parseInt1;
                        int parseInt2;
                        try {
                            parseInt1 = Integer.parseInt(split1);
                            parseInt2 = Integer.parseInt(split2);
                        } catch (NumberFormatException e) {//如果是非数字,按照原来的顺序
                            return 0;
                        }
                        if (parseInt1 > parseInt2) {
                            return 1;
                        } else {
                            return -1;
                        }
                    });
                    int size = sortList.size();
                    for (int i = 0; i < size; i++) {
                        System.out.println(sortList.get(i));
                        if (i == size - 1) {
                            fw.append(sortList.get(i));
                            break;
                        }
                        fw.append(sortList.get(i) + "+");
                        fw.flush();
                    }
                    fw.append(" new.mp4");
                    fw.flush();
                    fw.close();
                }
            }
            callCmd(runFilePath);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fw != null) {
                fw.close();
            }
        }
    }


    private static void callCmd(String locationCmd) {
        StringBuilder sb = new StringBuilder();
        InputStream in = null;
        BufferedReader bufferedReader = null;
        try {
            Process child = Runtime.getRuntime().exec(locationCmd);
            in = child.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line + "\n");
            }
            bufferedReader.close();
            in.close();
            try {
                child.waitFor();
            } catch (InterruptedException e) {
                System.out.println(e);
            }
            System.out.println("sb:" + sb.toString());
            System.out.println("callCmd execute finished");
            //执行完成后,将执行文件删除。
            File file = new File(locationCmd);
            file.delete();
        } catch (IOException e) {
            System.out.println(e);
        } finally {
            try {
                //将流关闭,从小往大关,防止流未关闭占用内存
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
            }
        }
    }


}

posted @ 2024-07-17 23:04  cxf0616  阅读(74)  评论(0编辑  收藏  举报