音頻處理工具ffmpeg的簡單使用

1、去官網下載

傳送門: http://ffmpeg.org

2、使用ffmpeg將視頻.mp4轉成音頻.avi

clipboard.png

clipboard.png

3、截取視頻的封面

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();
        }
    }

4、將視頻和音樂合併在一塊兒,即爲視頻選一首背景音樂

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();
        }

    }
相關文章
相關標籤/搜索