親測可用,基於ffmpeg 去進行壓縮,
測試原視頻大小:835.87 MB
壓縮后大小:118.8 MB
壓縮比率 :85.78%
壓縮視頻jar包源碼地址 : https://github.com/a-schild/jave2
好了,開始上代碼
1、首先 pom文件中引入下面兩個 jar 包
<dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-core</artifactId>
<version>2.7.3</version>
</dependency>
具體引用包按本機操作系統來設定
<dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-nativebin-osx64</artifactId>
<version>2.7.3</version>
</dependency>
java 代碼
/**
* 傳遠程視頻連接,返回壓縮后File
*/
public static File compressionVideo(String href){
try{
// 緩存到臨時目錄,壓縮上傳完到遠程服務器上之后,記得刪除源視頻
String savePath = "/tmp/tempVideo/";
long time = System.currentTimeMillis();
URL url=new URL(href);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
connection.setConnectTimeout(600*1000);
connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36");
InputStream in=connection.getInputStream();
String fileName = "zip" + href.substring(href.lastIndexOf("/") + 1);
File saveDir = new File(savePath);
if(!saveDir.exists()){
saveDir.mkdirs();
}
File file = new File(savePath + fileName);
OutputStream out=new FileOutputStream(file);
byte[] bytes=new byte[1024];
int len = 0;
while((len=in.read(bytes))!=-1){
out.write(bytes,0,len);
}
out.close();
in.close();
System.out.println("下載+壓縮 總耗時:" + (System.currentTimeMillis() - time)/1000);
return compressionVideo(file, fileName);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
/**
* 傳視頻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("/")).concat(picName);
File target = new File(newPath);
try {
MultimediaObject object = new MultimediaObject(source);
AudioInfo audioInfo = object.getInfo().getAudio();
// 根據視頻大小來判斷是否需要進行壓縮,
int maxSize = 100;
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 ");
// 視頻 > 100MB, 或者每秒 > 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();
// 設置通用編碼格式
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 視頻編碼屬性配置
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;
}
/**
* 獲取視頻大小
* @param source
* @return
*/
@SuppressWarnings({ "resource" })
public static BigDecimal ReadVideoSize(File source) {
FileChannel fc = null;
try {
FileInputStream fis = new FileInputStream(source);
fc = fis.getChannel();
BigDecimal fileSize = new BigDecimal(fc.size());
return fileSize.divide(new BigDecimal(1048576), 2, RoundingMode.HALF_UP);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != fc) {
try {
fc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
##測試
public static void main(String[] args) throws Exception{
String savePath = "/tmp/tempVideo/";
File saveDir = new File(savePath);
if(!saveDir.exists()){
saveDir.mkdirs();
}
File file = compressionVideo("http://xxxx.mp4");
System.out.println(file.getName());
}