- 开源项目 JAVE (Java Audio Video Encoder)
- 引入依赖
<dependency> <groupId>ws.schild</groupId> <artifactId>jave-all-deps</artifactId> <version>2.7.2</version> </dependency>
- 编码测试
package test; import java.io.File; import ws.schild.jave.AudioAttributes; import ws.schild.jave.AudioInfo; import ws.schild.jave.Encoder; import ws.schild.jave.EncodingAttributes; import ws.schild.jave.MultimediaInfo; import ws.schild.jave.MultimediaObject; import ws.schild.jave.VideoAttributes; import ws.schild.jave.VideoInfo; import ws.schild.jave.VideoSize; public class Test { public static void main(String[] args) throws Exception { File source = new File("d:/source.mp4"); File target = new File("d:/target.mp4"); System.out.println("源视频信息"); MultimediaObject object = new MultimediaObject(source); MultimediaInfo info = object.getInfo(); System.out.println("格式format:" + info.getFormat()); System.out.println("时长duration:" + info.getDuration()); VideoInfo videoInfo = info.getVideo(); System.out.println("编码decoder:" + videoInfo.getDecoder()); System.out.println("码率bitRate:" + videoInfo.getBitRate()); System.out.println("帧率frameRate:" + videoInfo.getFrameRate()); VideoSize videoSize = videoInfo.getSize(); System.out.println("分辨率:" + videoSize.getWidth() + " x " + videoSize.getHeight()); AudioInfo audioInfo = info.getAudio(); System.out.println("编码decoder:" + audioInfo.getDecoder()); System.out.println("码率bitRate:" + audioInfo.getBitRate()); System.out.println("声道channels:" + audioInfo.getChannels()); System.out.println("采样率samplingRate:" + audioInfo.getSamplingRate()); // 视频属性 VideoAttributes video = new VideoAttributes(); video.setCodec("libx264"); video.setBitRate(256000); // 码率:256kbps video.setFrameRate(25); // 帧率:25fps int width = 640; // 固定宽度 int height = width * videoSize.getHeight() / videoSize.getWidth(); height = height%2==0 ? height : height+1; // 视频宽高必须是偶数 video.setSize(new VideoSize(width, height)); // 音频属性 AudioAttributes audio = new AudioAttributes(); audio.setCodec("aac"); audio.setBitRate(64000); // 码率:64kbps audio.setSamplingRate(24000); // 采样率:24kHz // 转码属性 EncodingAttributes attributes = new EncodingAttributes(); attributes.setVideoAttributes(video); attributes.setAudioAttributes(audio); attributes.setFormat("mp4"); Encoder encoder = new Encoder(); encoder.encode(object, target, attributes); System.out.println("转码完成:新分辨率:" + width + " x " + height); } }
- 测试结果
源视频信息 格式format:mov 时长duration:268280 编码decoder:h264 (Main) (avc1 / 0x31637661) 码率bitRate:500000 帧率frameRate:25.0 分辨率:768 x 432 编码decoder:aac (LC) (mp4a / 0x6134706D) 码率bitRate:96000 声道channels:2 采样率samplingRate:44100 转码完成:新分辨率:640 x 360