因为项目需求中涉及到视频中音频提取,以及字幕压缩的功能,一直在研究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 ""; } }