java视频压缩亲测有效,无需插件

依赖 

		
		
			ws.schild
			jave-core
			3.0.0
		
		
		
			ws.schild
			jave-nativebin-win64
			3.0.0
		
		
		
			ws.schild
			jave-nativebin-linux64
			3.0.0
		

代码

picName不要和文件重名;不然报错

import ws.schild.jave.Encoder;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.encode.AudioAttributes;
import ws.schild.jave.encode.EncodingAttributes;
import ws.schild.jave.encode.VideoAttributes;
import ws.schild.jave.info.AudioInfo;
import ws.schild.jave.info.VideoInfo;

import java.io.File;
import java.math.BigDecimal;

/**
 * 视频压缩工具类
 */
public class VideoUtil {

    /**
     * 传视频File对象(这是一个具体的文件),返回压缩后File对象信息
     * @param source
     */
    public static File compressionVideo(File source,String picName) {
        if(source == null){
            return null;
        }
        String newPath = source.getAbsolutePath().substring(0, source.getAbsolutePath().lastIndexOf(File.separator)).concat(File.separator).concat(picName);
        File target = new File(newPath);
        try {
            MultimediaObject object = new MultimediaObject(source);
            // 根据视频大小来判断是否需要进行压缩,
            int maxSize = 200;
            double mb = Math.ceil(source.length() / 1048576);
            int second = (int)object.getInfo().getDuration() / 1000;
            BigDecimal bd = new BigDecimal(String.format("%.4f", mb / second));
            System.out.println("开始压缩视频了--> 视频每秒平均 "+ bd +" MB ");
            // 视频 > 200MB, 或者每秒 > 0.5 MB 才做压缩
            boolean temp = mb > maxSize || bd.compareTo(new BigDecimal(0.5)) > 0;
            if(temp){
                long time = System.currentTimeMillis();
                // 视频压缩参数
                int maxAudioBitRate = 128000;
                int maxSamplingRate = 44100;
                int maxVideoBitRate = 800000;
                int maxFrameRate = 20;

                // 音频属性设置
                AudioInfo audioInfo = object.getInfo().getAudio();
                AudioAttributes audio = new AudioAttributes();
                // 设置音频比特率,单位:b (比特率越高,清晰度/音质越好,当然文件也就越大 128000 = 182kb)
                if(audioInfo.getBitRate() > maxAudioBitRate){
                    audio.setBitRate(new Integer(maxAudioBitRate));
                }
                // 设置重新编码的音频流中使用的声道数(1 =单声道,2 = 双声道(立体声))。
                // 如果未设置任何声道值,则编码器将选择默认值 0。
                audio.setChannels(audioInfo.getChannels());
                // 采样率越高声音的还原度越好,文件越大
                // 设置音频采样率,单位:赫兹 hz
                // 设置编码时候的音量值,未设置为0;如果256,则音量值不会改变
                audio.setVolume(256);
                if(audioInfo.getSamplingRate() > maxSamplingRate){
                    audio.setSamplingRate(maxSamplingRate);
                }

                // 视频编码属性配置
                VideoInfo videoInfo = object.getInfo().getVideo();
                VideoAttributes video = new VideoAttributes();
                //设置音频比特率,单位:b (比特率越高,清晰度/音质越好,当然文件也就越大 800000 = 800kb)
                if(videoInfo.getBitRate() > maxVideoBitRate){
                    video.setBitRate(maxVideoBitRate);
                }
                // 视频帧率:15 f / s  帧率越低,效果越差
                // 设置视频帧率(帧率越低,视频会出现断层,越高让人感觉越连续),视频帧率(Frame rate)是用于测量显示帧数的量度。
                // 所谓的测量单位为每秒显示帧数(Frames per Second,简:FPS)或“赫兹”(Hz)。
                if(videoInfo.getFrameRate() > maxFrameRate){
                    video.setFrameRate(maxFrameRate);
                }

                EncodingAttributes attr = new EncodingAttributes();
                attr.setOutputFormat("mp4");
                attr.setAudioAttributes(audio);
                attr.setVideoAttributes(video);
                // 设置线程数
                attr.setEncodingThreads(Runtime.getRuntime().availableProcessors()/2);

                Encoder encoder = new Encoder();
                encoder.encode(new MultimediaObject(source), target, attr);
                System.out.println("压缩总耗时:" + (System.currentTimeMillis() - time)/1000);
                return target;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(target.length() > 0){
                source.delete();
            }
        }
        return source;
    }

}

以上代码不行试以下

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.tomcat.util.http.ResponseUtil;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.SymbolConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.RestUtil;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.filter.FileTypeFilter;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.encode.AudioAttributes;
import ws.schild.jave.encode.EncodingAttributes;
import ws.schild.jave.encode.VideoAttributes;
import ws.schild.jave.info.AudioInfo;
import ws.schild.jave.info.VideoInfo;
import ws.schild.jave.info.VideoSize;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import ws.schild.jave.Encoder;
 
public  File compressionVideo(File source, String picName) {
        if(source == null){
            return null;
        }
        String newPath = source.getAbsolutePath().substring(0, source.getAbsolutePath().lastIndexOf(File.separator)).concat(File.separator).concat(picName);
        File target = new File(newPath);
        try {
            MultimediaObject object = new MultimediaObject(source);
            AudioInfo audioInfo = object.getInfo().getAudio();
            // 根据视频大小来判断是否需要进行压缩,
            int maxSize = 5;
            double mb = Math.ceil(source.length()/ 1048576);
            int second = (int)object.getInfo().getDuration()/1000;
            BigDecimal bd = new BigDecimal(String.format("%.4f", mb/second));
            System.out.println("开始压缩视频了--> 视频每秒平均 "+ bd +" MB ");
            // 视频 > 5MB, 或者每秒 > 0.5 MB 才做压缩, 不需要的话可以把判断去掉
            boolean temp = mb > maxSize || bd.compareTo(new BigDecimal(0.5)) > 0;
            if(temp){
            long time = System.currentTimeMillis();
            //TODO 视频属性设置
            int maxBitRate = 12800;
            int maxSamplingRate = 4410;
            int bitRate = 80000;
            int maxFrameRate = 5;
            int maxWidth = 128;

            AudioAttributes audio = new AudioAttributes();
            // 设置通用编码格式10                   audio.setCodec("aac");
            // 设置最大值:比特率越高,清晰度/音质越好
            // 设置音频比特率,单位:b (比特率越高,清晰度/音质越好,当然文件也就越大 128000 = 182kb)
            if(audioInfo.getBitRate() > maxBitRate){
                audio.setBitRate(new Integer(maxBitRate));
            }

            // 设置重新编码的音频流中使用的声道数(1 =单声道,2 = 双声道(立体声))。如果未设置任何声道值,则编码器将选择默认值 0。
            audio.setChannels(audioInfo.getChannels());
            // 采样率越高声音的还原度越好,文件越大
            // 设置音频采样率,单位:赫兹 hz
            // 设置编码时候的音量值,未设置为0,如果256,则音量值不会改变
            // audio.setVolume(256);
            if(audioInfo.getSamplingRate() > maxSamplingRate){
                audio.setSamplingRate(maxSamplingRate);
            }

            //TODO 视频编码属性配置
            ws.schild.jave.info.VideoInfo videoInfo = object.getInfo().getVideo();
            VideoAttributes video = new VideoAttributes();
            video.setCodec("h264");
            //设置音频比特率,单位:b (比特率越高,清晰度/音质越好,当然文件也就越大 800000 = 800kb)
            if(videoInfo.getBitRate() > bitRate){
                video.setBitRate(bitRate);
            }

            // 视频帧率:15 f / s  帧率越低,效果越差
            // 设置视频帧率(帧率越低,视频会出现断层,越高让人感觉越连续),视频帧率(Frame rate)是用于测量显示帧数的量度。所谓的测量单位为每秒显示帧数(Frames per Second,简:FPS)或“赫兹”(Hz)。
            if(videoInfo.getFrameRate() > maxFrameRate){
                video.setFrameRate(maxFrameRate);
            }

            // 限制视频宽高
            int width = videoInfo.getSize().getWidth();
            int height = videoInfo.getSize().getHeight();
            if(width > maxWidth){
                float rat = (float) width / maxWidth;
                video.setSize(new VideoSize(maxWidth,(int)(height/rat)));
            }

            EncodingAttributes attr = new EncodingAttributes();
            attr.setOutputFormat("mp4");
            attr.setAudioAttributes(audio);
            attr.setVideoAttributes(video);

            // 速度最快的压缩方式, 压缩速度 从快到慢: ultrafast, superfast, veryfast, faster, fast, medium,  slow, slower, veryslow and placebo.
//                attr.setPreset(PresetUtil.VERYFAST);
//                attr.setCrf(27);
//                // 设置线程数
                attr.setEncodingThreads(Runtime.getRuntime().availableProcessors()/2);

            Encoder encoder = new Encoder();
            encoder.encode(new MultimediaObject(source), target, attr);
            System.out.println("压缩总耗时:" + (System.currentTimeMillis() - time)/1000);
            return target;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(target.length() > 0){
                source.delete();
            }
        }
        return source;
    }

文件转换工具

前端接收的文件格式为:MultipartFile
后端需要转换为:File

import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class MultipartFileAndFileUtils {

    /**
     * MultipartFile 转 File
     * @param file
     * @throws Exception
     */
    public static File toFile(MultipartFile file) throws Exception {
        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    /**
     *  File 转 MultipartFile
     * @param file
     * @throws Exception
     */
    public static MultipartFile toMultipartFile(File file) throws Exception {
        InputStream inputStream = new FileInputStream(file);
        MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),"application/octet-stream", inputStream);
        return multipartFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除本地临时文件
     * @param file
     */
    public static void delteTempFile(File file) {
        if (file != null) {
            File del = new File(file.toURI());
            del.delete();
        }
    }

}

关于报错
ws.schild.jave.EncoderException: Exit code of ffmpeg encoding run is 1
是因为代码来设置了 setCodec;默认不传也可以压缩。
注:一个800M的文件可以压缩到400M左右;我本地测试压缩时间为30分钟左右。
linuxu环境没有测试;可参考以下文章进行配置。
原文链接:https://blog.csdn.net/qq_43619832/article/details/124062598

                JAVA,实现视频压缩(最全)_ffmpeg-amd64-3.0.0.exe-CSDN博客

  • 注意
  • linux下,Java io 的临时路径下要有这个文件ffmpeg-amd64-3.0.0,如果没有这个文件,在依赖的jar包中(jave-nativebin-win64)获取,手动放上。

你可能感兴趣的:(java,开发语言)