JAVA,实现视频压缩(最全)

说明

Java压缩视频大小,10M视频压缩完成后大约是1M,用时大约2S
技术:基于 fffmpeg 技术实现视频压缩
条件:需要maven引入jar包

步骤一
  1. 引入pom基础依赖(前提是maven工程,在 pom.xml 文件中添加如下行)
    <dependency>
        <groupId>ws.schild</groupId>
        <artifactId>jave-core</artifactId>
        <version>3.0.0</version>
    </dependency>
  1. 依据服务器操作系统来设定如下包(此处我是用win10-64位),部署到服务器一般是linux,所以建议下面行都加入 pom.xml文件中
    <!-- 在windows上开发 开发机可实现压缩效果 window64位 -->
    <dependency>
        <groupId>ws.schild</groupId>
        <artifactId>jave-nativebin-win64</artifactId>
        <version>3.0.0</version>
    </dependency>
    
    <!-- 在linux上部署 linux服务器需要这个才能生效 linux64位 -->
    <dependency>
        <groupId>ws.schild</groupId>
        <artifactId>jave-nativebin-linux64</artifactId>
        <version>3.0.0</version>
    </dependency>
    
步骤二

具体的代码(压缩视频)

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.VideoSize;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.FileChannel;
	/**
     * 传视频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);
            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 = 128000;
                int maxSamplingRate = 44100;
                int bitRate = 800000;
                int maxFrameRate = 20;
                int maxWidth = 1280;

                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.setFormat("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;
    }

注意事项

正常只在windows操作系统上开发代码没问题。
但是部署到linux上跑项目,还需要2个步骤:

1.在刚刚依赖的jar包中,找到箭头文件夹
在这里插入图片描述
上面箭头点进去,找到下面箭头文件
在这里插入图片描述
把它复制到桌面并解压它,得到如下 数字1 文件:
在这里插入图片描述
你需要重命名为跟pom.xml版本一致的名字,也就是 数字2 那个文件。

2.把数字2文件,复制丢到linux服务器的 /tmp/java 路径下(99%的linux服务器是这样的路径,如果没有就创建文件夹并丢进去)

提醒:如果“ffmpeg-amd64-3.0.0” 文件丢到 “ /tmp/java ”不起作用,建议到报错的代码,也就是下面这儿检查(我就是看源码解决的)

MultimediaObject object = new MultimediaObject(source);

或者到类 DefaultFFMPEGLocator.class 中看具体使用哪个路径,但是大部分都是 /tmp/java路径,相信我!!!!!!!!

### 回答1: 以下是使用 Java 进行视频压缩的简单示例代码: ``` import org.bytedeco.ffmpeg.global.avcodec; import org.bytedeco.javacv.FFmpegFrameGrabber; import org.bytedeco.javacv.FFmpegFrameRecorder; import org.bytedeco.javacv.Frame; public class VideoCompress { public static void main(String[] args) throws Exception { // 输入文件路径 String inputFile = "input.mp4"; // 输出文件路径 String outputFile = "output.mp4"; // 获取输入视频的宽高 FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFile); grabber.start(); int width = grabber.getImageWidth(); int height = grabber.getImageHeight(); grabber.stop(); // 设置输出视频的宽高(可以调整输出视频的宽高来达到压缩的效果) int outWidth = 640; int outHeight = 480; // 初始化视频录制器 FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputFile, outWidth, outHeight); recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264); // 设置视频编码 recorder.setFormat("mp4"); // 设置视频输出格式 recorder.setFrameRate(30); // 设置帧率 recorder.setGopSize(30); // 设置关键帧间隔 recorder.start(); // 从输入文件读取帧并写入到输出文件 grabber.start(); while (true) { Frame frame = grabber.grabFrame(); if (frame == null) { break; } recorder.record(frame); } grabber.stop(); recorder.stop(); } } ``` 该代码使用了 JavaCV 库来进行视频处理。它使用 FFmpegFrameGrabber 类来读取输入视频文件的帧,然后使用 FFmpegFrameRecorder 类将帧写入到输出文 ### 回答2: 在Java中进行视频压缩可以使用FFmpeg库来实现。FFmpeg是一个开源的跨平台音视频处理工具,具有强大的功能和广泛的应用。 首先,需要在Java项目中引入FFmpeg库。可以通过在pom.xml文件中添加依赖,或者手动下载并导入库的jar文件。 要进行视频压缩,可以使用FFmpeg提供的命令行工具,在Java代码中调用命令行执行压缩操作。例如,以下是一个简单的示例: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class VideoCompressor { public static void main(String[] args) { String inputFilePath = "input.mp4"; String outputFilePath = "output.mp4"; String ffmpegCmd = "ffmpeg -i " + inputFilePath + " -vcodec libx264 -crf 24 " + outputFilePath; try { Process process = Runtime.getRuntime().exec(ffmpegCmd); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream())); String line; while ((line = reader.readLine()) != null) { // 输出FFmpeg的输出信息 System.out.println(line); } process.waitFor(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } } ``` 在上面的示例中,我们使用FFmpeg的命令行工具执行视频压缩操作。其中,`ffmpeg`是要执行的命令,`-i`后面跟上要压缩的视频文件路径,`-vcodec`指定视频编码格式,`-crf`是压缩质量参数,数值越大压缩得越多。 执行上述代码后,视频文件会被压缩,并保存为`output.mp4`。 需要注意的是,FFmpeg的命令行工具需要系统环境中已安装其可执行文件。在使用时,可以根据实际需求调整压缩参数和命令执行的方式。 ### 回答3: 下面是一个使用Java进行视频压缩的代码示例: ```java import ws.schild.jave.*; public class VideoCompressor { public static void main(String[] args) { try { // 设置输入文件路径和输出文件路径 String inputFilePath = "input.mp4"; String outputFilePath = "output.mp4"; // 创建输入文件对象和输出文件对象 File inputFile = new File(inputFilePath); File outputFile = new File(outputFilePath); // 创建编码器对象,这里使用默认的x264编码器 Encoder encoder = new Encoder(); // 创建压缩参数对象 EncodingAttributes attributes = new EncodingAttributes(); attributes.setFormat("mp4"); // 设置输出格式为MP4 attributes.setVideoCodec("mpeg4"); // 设置视频编码器为MPEG4 attributes.setAudioCodec("aac"); // 设置音频编码器为AAC // 设置压缩质量,取值范围为0.1-1.0 attributes.setQuality(0.5f); // 压缩视频 encoder.encode(new MultimediaObject(inputFile), outputFile, attributes); System.out.println("视频压缩完成!"); } catch (EncoderException e) { e.printStackTrace(); } } } ``` 以上代码使用了第三方库JAVE(Java Audio Video Encoder)来进行视频压缩。在代码中,首先设置输入文件路径和输出文件路径,然后创建输入文件对象和输出文件对象。接下来,创建编码器对象和压缩参数对象,并设置输出格式、视频编码器、音频编码器以及压缩质量等参数。最后,调用编码器的`encode()`方法进行视频压缩,并指定输入文件、输出文件和压缩参数作为参数。
评论 65
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值