1

一、去官网下载

传送门:http://ffmpeg.org

二、使用ffmpeg将视频.mp4转成音频.avi

clipboard.png

clipboard.png

三、截取视频的封面

clipboard.png

public void getCover(String videoInputPath, String coverOutputPath) throws IOException, InterruptedException {
//        ffmpeg.exe -ss 00:00:01 -i spring.mp4 -vframes 1 bb.jpg
        List<String> command = new java.util.ArrayList<String>();
        command.add(ffmpegEXE);
        
        // 指定截取第1秒
        command.add("-ss");
        command.add("00:00:01");
                
        command.add("-y");
        command.add("-i");
        command.add(videoInputPath);
        
        command.add("-vframes");
        command.add("1");
        
        command.add(coverOutputPath);
        
        for (String c : command) {
            System.out.print(c + " ");
        }
        
        ProcessBuilder builder = new ProcessBuilder(command);
        Process process = builder.start();
        
        InputStream errorStream = process.getErrorStream();
        InputStreamReader inputStreamReader = new InputStreamReader(errorStream);
        BufferedReader br = new BufferedReader(inputStreamReader);
        
        String line = "";
        while ( (line = br.readLine()) != null ) {
        }
        
        if (br != null) {
            br.close();
        }
        if (inputStreamReader != null) {
            inputStreamReader.close();
        }
        if (errorStream != null) {
            errorStream.close();
        }
    }

四、将视频和音乐合并在一起,即为视频选一首背景音乐

clipboard.png

public void convertor(String videoInputPath, String mp3InputPath, double seconds, String videoOutputPath) throws IOException {
        //ffmpeg.exe -i dormitory.mp4 -i bgm.mp3 -t 6 -y 新的视频.mp4
        List<String> command = new ArrayList<String>();
        command.add(ffmpegEXE);
        command.add("-i");
        command.add(videoInputPath);
        command.add("-i");
        command.add(mp3InputPath);
        command.add("-t");
        command.add(String.valueOf(seconds));

//        command.add("-strict"); //linux环境下如果截图需要添加下面两个参数
//        command.add("-2");

        command.add("-y");
        command.add(videoOutputPath);

        ProcessBuilder processBuilder =  new ProcessBuilder(command);
        Process process = processBuilder.start();
        //如果内存中太多流,会把当前线程卡住,需要清理
        InputStream errorStream = process.getErrorStream();
        InputStreamReader inputStreamReader = new InputStreamReader(errorStream);
        BufferedReader br = new BufferedReader(inputStreamReader);
        String line = "";
        while((line=br.readLine()) != null){

        }
        if(br != null){
            br.close();
        }
        if(inputStreamReader != null){
            inputStreamReader.close();
        }
        if(errorStream != null){
            errorStream.close();
        }

    }

nathan
57 声望14 粉丝

时刻保持积极向上的心态和清醒的大脑!