因爲項目需求中涉及到視頻中音頻提取,以及字幕壓縮的功能,一直在研究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
說明:字體
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 ""; } }