FFmpeg在JAVA中的使用-音頻提取&字幕壓縮

  因爲項目需求中涉及到視頻中音頻提取,以及字幕壓縮的功能,一直在研究ffmpeg,僅僅兩個功能,卻深受ffmpeg的折磨。html

  今天談談ffmpeg在java中的簡單使用,首先下載FFmpeg包,官方地址:http://ffmpeg.org/download.html,這裏建議下載Linux Static Builds版本的,輕小並且解壓後能夠直接使用,我使用的版本是ffmpeg-git-20170922-64bit-static.tar.xz。java

  解壓以後,文件夾中有一個可執行文件ffmpeg,在linux上能夠直接運行./ffmpeg -version,能夠查看ffmpeg的版本信息,以及configuration配置信息。linux

  如今,能夠使用ffmpeg的相關命令來進行一些操做:git

  1.視頻中音頻提取:ffmpeg -i [videofile]  -vn -acodec copy [audiofile]網絡

  2.字幕壓縮至視頻中:ffmpeg -i [videofile]  -vf subtitles=[subtitle.srt] [targetvideofile]dom

  3.其它相關命令能夠查閱:http://ffmpeg.org/ffmpeg.htmlide

  說明:字體

  • videofile是須要提取音頻的視頻源文件,能夠是本地文件,也能夠是網絡文件url。
  • subtitle.srt是字幕文件(中文字幕即把英文變爲中文,其它格式一致),這邊就使用最簡單的srt標準格式,以下所示:

  

  • 特別注意:srt文件寫入的字符編碼須要是UTF-8,不然壓縮的時候會報沒法讀取srt文件;
  • 若想壓縮中文字幕,須要系統中有中文字體,使用fc-list查詢系統支持的字體,fc-list :lang=zh查詢支持的中文字體
  • 相關java代碼以下:

  

public class FFMpegUtil {

    private static final Logger logger = Logger.getLogger(FFMpegUtil.class);

    // ffmpeg命令所在路徑
    private static final String FFMPEG_PATH = "/ffmpeg/ffmpeg";
    // ffmpeg處理後的臨時文件
    private static final String TMP_PATH = "/tmp";
    // home路徑
    private static final String HOME_PATH;

    static {
        HOME_PATH = System.getProperty("user.home");
        logger.info("static home path : " + HOME_PATH);
    }

    /**
     * 視頻轉音頻
     * @param videoUrl
     */
    public static String videoToAudio(String videoUrl){
        String aacFile = "";
        try {
            aacFile = TMP_PATH + "/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
                    + UUID.randomUUID().toString().replaceAll("-", "") + ".aac";
            String command = HOME_PATH + FFMPEG_PATH + " -i "+ videoUrl + " -vn -acodec copy "+ aacFile;
            logger.info("video to audio command : " + command);
            Process process = Runtime.getRuntime().exec(command);
            process.waitFor();
        } catch (Exception e) {
            logger.error("視頻轉音頻失敗,視頻地址:"+videoUrl, e);
        }
        return "";
    }
    
    /**
     * 將字幕燒錄至視頻中
     * @param videoUrl
     */
    public static String burnSubtitlesIntoVideo(String videoUrl, File subtitleFile){
        String burnedFile = "";
        File tmpFile = null;
        try {
            burnedFile = TMP_PATH + "/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
                    + UUID.randomUUID().toString().replaceAll("-", "") + ".mp4";
            String command = HOME_PATH + FFMPEG_PATH + " -i "+ videoUrl + " -vf subtitles="+ subtitleFile +" "+ burnedFile;
            logger.info("burn subtitle into video command : " + command);
            Process process = Runtime.getRuntime().exec(command);
            process.waitFor();
        } catch (Exception e) {
            logger.error("視頻壓縮字幕失敗,視頻地址:"+videoUrl+",字幕地址:"+subtitleUrl, e);
        }
        return "";
    }
}
相關文章
相關標籤/搜索