使用FFmpeg粗加工处理视频转码、截封面图 (2)

689 阅读1分钟

java使用FFmpeg粗加工处理视频转码、截封面图

这是我参与更文挑战的第12天,活动详情查看: 更文挑战

使用FFmpeg粗加工处理视频转码、截封面图 (1)

业务场景:

通过java对上传的视频进行转码,然后将视频上传到文件存储服务器

视频处理工具类VideoUtil

 package com.ozx.util;
 
 import it.sauronsoftware.jave.*;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.web.multipart.MultipartFile;
 
 import java.io.BufferedReader;
 import java.io.File;
 import java.io.IOException;
 import java.io.InputStreamReader;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.UUID;
 
 /**
  * @author Gxin
  * @date 2021/6/26 11:09
  */
 public class VideoUtil {
 
     /**
      * 路径的配置可以放在配置文件里导入进来
      */
     private final static String FFMPEG_PATH = "E:\\FFmpeg\\ffmpeg-4.2.1-win64-static\\bin\\ffmpeg.exe";
     private final static String SOURCE = "C:\\Users\\VULCAN\\Desktop\\test1\\";
     private final static String TARGET = "C:\\Users\\VULCAN\\Desktop\\test2\\";
 
     //设置截图大小
     private final static String IMAGE_SIZE = "800x600";
     //设置截图的时间点
     private final static String IMAGE_TIME = "00:00:02";
 
     private final static Logger logger = LoggerFactory.getLogger(VideoUtil.class);
 
     /**
      * 将上传过来的视频转换成mp4格式并截图
      */
     public static List<String> transformAndCompressVideo(MultipartFile file) {
         List<String> list = new ArrayList<>(0);
         //将视频转换成MP4格式
         String prefix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
         //临时文件路径作为转换源
         String sourceVideoPath = SOURCE + UUID.randomUUID().toString().replace("-", "") + prefix;
         File source = new File(sourceVideoPath);
         try {
             file.transferTo(source);
         } catch (Exception e) {
             logger.error("multipartFile转换成file失败,{}", e);
         }
         //转换后目的文件路径
         String targetVideoPath = TARGET + UUID.randomUUID().toString().replace("-", "") + ".mp4";
         File target = new File(targetVideoPath);
         //音频属性
         AudioAttributes audio = new AudioAttributes();
         //设置音频编码 libFaac PGM编码
         audio.setCodec("libmp3lame");
         //设置音频比特率
         audio.setBitRate(new Integer(56000));
         //设置音频声道
         audio.setChannels(new Integer(1));
         //设置音频采样率
         audio.setSamplingRate(new Integer(22050));
         //视频属性
         VideoAttributes video = new VideoAttributes();
         //设置视频编码
         video.setCodec("mpeg4");
         //设置视频比特率,比特率越大越清晰,文件也会越大
         video.setBitRate(new Integer(1200000));
         //设置视频帧率,帧率越大越流畅连贯
         video.setFrameRate(new Integer(25));
         //转码属性
         EncodingAttributes attr = new EncodingAttributes();
         //设置视频格式
         attr.setFormat("mp4");
         //设置音频属性
         attr.setAudioAttributes(audio);
         //设置视频属性
         attr.setVideoAttributes(video);
         //创建转码器
         Encoder encoder = new Encoder();
         try {
             encoder.encode(source, target, attr);
         } catch (Exception e) {
             logger.error("视频格式转换失败,{}", e);
         }
         //视频截取第2s的帧作为封面图
         String targetImagePath = TARGET + UUID.randomUUID().toString().replace("-", "") + ".jpg";
         File imageTarget = new File(targetImagePath);
         covPic(sourceVideoPath, IMAGE_TIME, targetImagePath, IMAGE_SIZE);
         list.add(sourceVideoPath);
         //上传到存储服务器后要删除掉本地文件把targetVideoPath和targetImagePath也加进来
         return list;
     }
 }

视频转码并截封面图片测试类

    package com.ozx.util;
    
    import com.ozx.mybatisplus.utils.video.VideoUtil;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.poi.util.IOUtils;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.mock.web.MockMultipartFile;
    import org.springframework.test.context.junit4.SpringRunner;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.util.List;
    
    /**
     * @author Gxin
     * @date 2021/6/26 15:05
     */
    @RunWith(SpringRunner.class)
    @SpringBootTest
    @Slf4j
    public class VideoTest {
        @Test
        public void test1() {
            List<String> fileList = null;
            try {
                File file = new File("C:\\Users\\VULCAN\\Desktop\\test\\test2.wmv");
                FileInputStream fis = new FileInputStream(file);
                MultipartFile multipartFile = new MockMultipartFile("file", file.getName(),"text/plain", IOUtils.toByteArray(fis));
                fileList = VideoUtil.transformAndCompressVideo(multipartFile);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //完成转码上传后删除临时文件
                for (String filePath : fileList) {
                    File file = new File(filePath);
                    VideoUtil.deleteFile(file);
                }
            }
        }
    }
    ```