由於項目需求中涉及到視頻中音頻提取,以及字幕壓縮的功能,一直在研究ffmpeg,僅僅兩個功能,卻深受ffmpeg的折磨。
今天談談ffmpeg在java中的簡單使用,首先下載FFmpeg包,官方地址:http://ffmpeg.org/download.html,這里建議下載Linux Static Builds版本的,輕小而且解壓后可以直接使用,我使用的版本是ffmpeg-git-20170922-64bit-static.tar.xz。
解壓之后,文件夾中有一個可執行文件ffmpeg,在linux上可以直接運行./ffmpeg -version,可以查看ffmpeg的版本信息,以及configuration配置信息。
現在,可以使用ffmpeg的相關命令來進行一些操作:
1.視頻中音頻提取:ffmpeg -i [videofile] -vn -acodec copy [audiofile]
2.字幕壓縮至視頻中:ffmpeg -i [videofile] -vf subtitles=[subtitle.srt] [targetvideofile]
3.其它相關命令可以查閱:http://ffmpeg.org/ffmpeg.html
說明:
- 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 ""; } }
