java實現視頻格式轉換為mp4


1.基於上一篇繼續,根據需求將其他視頻格式轉換為mp4格式后前端能預覽資源視頻

2.首先需要准備的工作是要准備外部文件轉換器,下載文件后直接解壓如下,按照這個路徑下指定,linux下需要安裝才能進行

鏈接:https://pan.baidu.com/s/1N_MURcIJdIVl9sKgod1rGA
提取碼:h3q9

 

 

3.最后的代碼工具類如下:

 

package file;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class ConvertVideo {

    private static String ffmpegPath  = "C:/server/ffmpeg/bin/win64/ffmpeg.exe";

    private static String mplayerPath = "C:/server/mencoder/mencoder.exe";


    /**
     * 視頻格式轉換入口
     *
     * @param inputPath  源文件 路徑
     * @param outputPath 目標文件 路徑
     * @param outputPath1 中間文件地址 路徑
     * @return
     */
    public synchronized static boolean process(String inputPath, String outputPath ,String outputPath1) {
        int type = checkContentType(inputPath);
        boolean status = false;
        Long old = System.currentTimeMillis();
        System.out.println("old--------" + old);
        if (type == 0) {
            System.out.println("直接轉成MP4格式");
            status = processMP4(inputPath, outputPath);// 直接轉成flv格式
        } else if (type == 1) {
            String avifilepath = processAVI(inputPath, outputPath1);
            System.out.println(avifilepath);
            if (avifilepath == null)
                return false;// 沒有得到avi格式
            status = processMP4(avifilepath, outputPath);// 將avi轉成flv格式
        }
        Long yong = System.currentTimeMillis();
        System.out.println("消耗時間----------" + (yong-old));
        return status;
    }

    /**
     * 判斷文件類型.執行不同的轉換流程
     *
     * @param inputPath 源文件路徑
     * @return
     */
    private static int checkContentType(String inputPath) {
        String type = inputPath.substring(inputPath.lastIndexOf(".") + 1, inputPath.length())
                .toLowerCase();
        // ffmpeg能解析的格式:(asx,asf,mpg,wmv,3gp,mp4,mov,avi,flv等)
        if (type.equals("avi")) {
            return 0;
        } else if (type.equals("mpg")) {
            return 0;
        } else if (type.equals("wmv")) {
            return 0;
        } else if (type.equals("3gp")) {
            return 0;
        } else if (type.equals("mov")) {
            return 0;
        } else if (type.equals("mp4")) {
            return 0;
        } else if (type.equals("asf")) {
            return 0;
        } else if (type.equals("asx")) {
            return 0;
        } else if (type.equals("flv")) {
            return 0;
        }
        // 對ffmpeg無法解析的文件格式(wmv9,rm,rmvb等),
        // 可以先用別的工具(mencoder)轉換為avi(ffmpeg能解析的)格式.
        else if (type.equals("wmv9")) {
            return 1;
        } else if (type.equals("rm")) {
            return 1;
        } else if (type.equals("rmvb")) {
            return 1;
        }
        return 9;
    }

    /**
     * 判斷源文件是否存在
     *
     * @param path 文件路徑
     * @return
     */
    private static boolean checkfile(String path) {
        File file = new File(path);
        if (!file.isFile()) {
            return false;
        }
        return true;
    }

    // 對ffmpeg無法解析的文件格式(wmv9,rm,rmvb等), 可以先用別的工具(mencoder)轉換為avi(ffmpeg能解析的)格式.
    private static String processAVI(String inputPath, String outputPath1) {
        List<String> commend = new ArrayList<>();
        commend.add(mplayerPath);
        commend.add(inputPath);
        commend.add("-oac");
        commend.add("mp3lame");
        commend.add("-lameopts");
        commend.add("preset=64");
        commend.add("-ovc");
        commend.add("xvid");
        commend.add("-xvidencopts");
        commend.add("bitrate=600");
        commend.add("-of");
        commend.add("avi");
        commend.add("-o");
        commend.add(outputPath1);
        try {
            ProcessBuilder builder = new ProcessBuilder();
            Process process = builder.command(commend).redirectErrorStream(true).start();
            new PrintStream(process.getInputStream()).start();
            new PrintStream(process.getErrorStream()).start();
            process.waitFor();
            process.destroy();
            return outputPath1;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // ffmpeg能解析的格式:(asx,asf,mpg,wmv,3gp,mp4,mov,avi,flv等) 轉換為MP4
    private static boolean processMP4(String inputPath, String outputPath) {

        if (!checkfile(inputPath)) {
            System.out.println(inputPath + " is not file");
            return false;
        }

        List<String> command = new ArrayList<>();
        command.add(ffmpegPath);
        command.add("-i");
        command.add(inputPath);
        command.add("-c:v");
        command.add("libx264");
        command.add("-mbd");
        command.add("0");
        command.add("-c:a");
        command.add("aac");
        command.add("-strict");
        command.add("-2");
        command.add("-pix_fmt");
        command.add("yuv420p");
        command.add("-movflags");
        command.add("faststart");
        command.add(outputPath);
        try {
            Process videoProcess = new ProcessBuilder(command).redirectErrorStream(true).start();

            new PrintStream(videoProcess.getErrorStream()).start();

            new PrintStream(videoProcess.getInputStream()).start();

            videoProcess.waitFor();
            videoProcess.destroy();
            System.out.println(outputPath);
            return true;
        } catch (Exception e) {

            return false;
        }
    }
    public static void main(String[] args) {
        //本地文件地址
        String inputPath = "E:/test/11.flv";
        //目標文件地址
        String outputPath ="E:/video/11.mp4";
        //中間文件隨機數
        String uuidname = UUID.randomUUID().toString();
        //中間文件地址,需要兩次轉換的情況下會用到該中間文件.直接轉換為MP4的文件不會生成中間文件.
        String path = "E:/video/";
        String outputPath1 = path  + uuidname + ".avi";
        //執行轉換
        ConvertVideo.process(inputPath,outputPath,outputPath1);//執行完畢后可以刪除沒用的文件

    }
}

/**
 * 資源釋放流.避免內存溢出導致進程阻塞
 */
class PrintStream extends Thread {

    java.io.InputStream __is = null;

    public PrintStream(java.io.InputStream is) {
        __is = is;
    }

    public void run() {
        try {
            while (this != null) {
                int _ch = __is.read();
                if (_ch != -1)
                    System.out.print((char) _ch);
                else break;
            }
            __is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



}

 

按照上述操作即可將視頻轉換為mp4,目前支持能支持大部分常見視頻格式轉換為mp4文件,有其他不能轉換的格式可以提出來一起討論下;

最后的最后將源碼貼出來,有需要的小伙伴可以試試;

鏈接:https://pan.baidu.com/s/1pX-7A-4E_fNBGnSH8mZFWw
提取碼:mrx8

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM