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 "";
    }
}
相关文章
相关标签/搜索