java mencoder_java 用ffmpeg和mencoder进行视频转码
1.準備階段:首先需要ffmpeg.exe和mencoder.exe,java需要調用這兩個文件來進行轉碼。
drv43260.dll,pncrt.dll,pthreadGC2.dll? 為動態鏈接庫? ?必須有 ,否則 rm格式 文件利用mencoder轉換avi時會報如下錯誤
Opening?video?decoder:?[realvid]?RealVideo?decoder
Error?loading?dll
ERROR:?Could?not?open?required?DirectShow?codec?drvc.so.
Read?the?RealVideo?section?of?the?DOCS!
VDecoder?init?failed?:(
Opening?video?decoder:?[realvid]?RealVideo?decoder
Error?loading?dll
ERROR:?Could?not?open?required?DirectShow?codec?drv4.so.6.0.
Read?the?RealVideo?section?of?the?DOCS!
VDecoder?init?failed?:(
Opening?video?decoder:?[realvid]?RealVideo?decoder
Error?loading?dll
ERROR:?Could?not?open?required?DirectShow?codec?drv43260.dll.
Read?the?RealVideo?section?of?the?DOCS!
VDecoder?init?failed?:(
Opening?video?decoder:?[realvid]?RealVideo?decoder
Error?loading?dll
ERROR:?Could?not?open?required?DirectShow?codec?drvc.bundle/Contents/MacOS/drvc.
Read?the?RealVideo?section?of?the?DOCS!
VDecoder?init?failed?:(
Cannot?find?codec?matching?selected?-vo?and?video?format?0x30345652.
Read?DOCS/HTML/en/codecs.html!
--------------------------------------------------------------------------------------------------------------------
2.編碼階段:
轉碼類------FileUploadTools
package com.test.util;
import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.EncodingAttributes;
import it.sauronsoftware.jave.InputFormatException;
import it.sauronsoftware.jave.MultimediaInfo;
import it.sauronsoftware.jave.VideoAttributes;
import it.sauronsoftware.jave.VideoSize;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.http.HttpRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
public class FileUploadTool {
TransfMediaTools transfMediaTools=new TransfMediaTools();
//文件最大200M
private static long upload_maxsize=200*1024*1024;
// 文件允許格式
private static String[] allowFiles = { ".rar", ".doc", ".docx", ".zip",
".pdf", ".txt", ".swf", ".xlsx", ".gif", ".png", ".jpg", ".jpeg",
".bmp", ".xls", ".mp4", ".flv", ".ppt", ".avi", ".mpg", ".wmv",
".3gp", ".mov", ".asf", ".asx", ".vob", ".wmv9", ".rm", ".rmvb" };
//視頻格式
private static String[] videoFiles={".swf",".mp4", ".flv",".avi", ".mpg", ".wmv",".3gp", ".mov", ".asf", ".asx", ".vob", ".wmv9", ".rm", ".rmvb"};
//圖片格式
private static String[] photoFiles={".gif", ".png", ".jpg", ".jpeg",".bmp"};
// 允許轉碼的視頻格式(ffmpeg)
private static String[] allowFLV = { ".avi", ".mpg", ".wmv", ".3gp",".mov", ".asf", ".asx", ".vob" ,".mp4"};
// 允許的視頻轉碼格式(mencoder)
private static String[] allowAVI = { ".wmv9", ".rm", ".rmvb" };
//視頻時長 秒
private static int max_time=180;
public Object createFile(MultipartFile multipartFile,HttpServletRequest request,HttpSession session){
Map map=new HashMap();
FileEntity entity=new FileEntity();
boolean bflag=false;
int minute=0;
int seconde=0;
int time=0;
String fileName=multipartFile.getOriginalFilename().toString();
//判斷文件不能為空
if(multipartFile.getSize()!=0 && !multipartFile.isEmpty()){
bflag=true;
//判斷文件大小
if(multipartFile.getSize()<=upload_maxsize){
bflag=true;
//文件類型判斷
if(this.checkFileType(fileName)){
bflag=true;
try {
//獲取文件時長
CommonsMultipartFile cf=(CommonsMultipartFile) multipartFile;
DiskFileItem fi=(DiskFileItem) cf.getFileItem();
File source=fi.getStoreLocation();
Encoder encoder=new Encoder();
MultimediaInfo m=encoder.getInfo(source);
System.out.println("-------"+m.getDuration());
long ls=m.getDuration()/1000;
minute=(int) ((ls%3600)/60);
seconde=(int)(ls-minute*60);
time=(int) ls;
System.out.println("此視頻時長:"+minute+"分"+seconde+"秒, 總時長"+ls+"秒");
System.out.println("此視頻格式:"+m.getFormat());
} catch (InputFormatException e1) {
e1.printStackTrace();
} catch (EncoderException e1) {
e1.printStackTrace();
}
if(time<=max_time){
bflag=true;
}else{
bflag=false;
System.out.println("視頻時間過長");
map.put("code", 0);
map.put("msg", "視頻時間過長");
}
}else{
bflag=false;
System.out.println("文件類型不允許");
map.put("code", 0);
map.put("msg", "文件類型不允許");
}
}else{
bflag=false;
System.out.println("文件大小超范圍");
map.put("code", 0);
map.put("msg", "文件大小超范圍");
}
}else{
bflag=false;
System.out.println("文件為空");
map.put("code", 0);
map.put("msg", "文件為空");
}
if(bflag){
String path = "F://video/";
// 新的文件名
String newFileName = this.getName(fileName);
//文件擴展名
String fileEnd=this.getFileExt(fileName);
//上傳文件夾
File targetFile = new File(path,newFileName+fileEnd);
//1.采用transferTo方法 上傳文件
//2.采用流方法上傳文件 防止 文件過大 網絡連接斷開上傳失敗
if (!targetFile.exists()) {
targetFile.mkdirs();
}
try {
multipartFile.transferTo(targetFile);
//BufferedOutputStream stream = new BufferedOutputStream(
// new FileOutputStream(targetFile));
// int length=0;
// byte[] buffer = new byte[1024];
// InputStream inputStream = multipartFile.getInputStream();
// while ((length = inputStream.read(buffer)) != -1) {
// stream.write(buffer, 0, length);
// }
//
// stream.flush();
// stream.close();
} catch (Exception e) {
e.printStackTrace();
}
// 1.邊上傳 邊壓縮
// File yasFile=new File(path+"123.mp4");
// try {
// // 音頻編碼設置
// AudioAttributes audio = new AudioAttributes();
// audio.setCodec("libmp3lame");
// audio.setBitRate(new Integer(64000));
// audio.setChannels(new Integer(1));
// audio.setSamplingRate(new Integer(22050));
// // 視頻編碼設置
// VideoAttributes video = new VideoAttributes();
// video.setCodec("flv");
// video.setBitRate(new Integer(160000));
// video.setFrameRate(new Integer(15));
// video.setSize(new VideoSize(400, 300));
// // 視頻轉碼編碼設置
// EncodingAttributes attrs = new EncodingAttributes();
// attrs.setFormat("flv");
// attrs.setAudioAttributes(audio);
// attrs.setVideoAttributes(video);
// // 編碼器
// Encoder encoder = new Encoder();
// encoder.encode(targetFile, yasFile, attrs);
//
// System.out.println("壓縮完成...");
// } catch (EncoderException e) {
// e.printStackTrace();
//
// }
//2. 先上傳 后壓縮 采用工具壓縮
String name = fileName.substring(0, fileName.lastIndexOf("."));
//壓縮文件夾
File yasuoFile=new File(path+"yasuo/");
if(!yasuoFile.exists()){
yasuoFile.mkdirs();
}
// 相對路徑
entity.setType(fileEnd);
String finalFileDir= "/filedizhi/video/yasuo/"+newFileName+fileEnd;
String size=this.getSize(targetFile);
String aviPath=targetFile.getAbsolutePath();
System.out.println("aviPath:"+aviPath);
//轉碼avi
if(this.checkAVIType(fileEnd)){
// 設置轉換為AVI格式后文件的保存路徑
String codcAviPath = path +"yasuo/"+ File.separator + newFileName + ".avi";
System.out.println("codcAviPath:"+codcAviPath);
// 獲取配置的轉換工具(mencoder.exe)的存放路徑? tools文件夾存放在WebContent下
String mencoderPath = request.getSession().getServletContext().getRealPath("tools/mencoder.exe");
aviPath = transfMediaTools.processAVI(mencoderPath, targetFile.getAbsolutePath(), codcAviPath);
fileEnd = this.getFileExt(codcAviPath);
}
if(aviPath!=null){
//轉碼Flv
if (this.checkMediaType(fileEnd)) {
try {
// 設置轉換為flv格式后文件的保存路徑
String codcFilePath = path +"yasuo/"+ File.separator + newFileName + ".flv";
System.out.println("codcFilePath:"+codcFilePath);
// 獲取配置的轉換工具(ffmpeg.exe)的存放路徑
String ffmpegPath =request.getSession().getServletContext().getRealPath("tools/ffmpeg.exe");
transfMediaTools.processFLV(ffmpegPath, aviPath, codcFilePath);
finalFileDir = "/filedizhi/video/yasuo/" + newFileName + ".flv";
} catch (Exception e) {
e.printStackTrace();
}
}
entity.setSize(size);
entity.setPath(finalFileDir);
entity.setTitleOrig(name);
entity.setTitleAlter(newFileName);
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
entity.setUploadTime(timestamp);
map.put("code", 1);
map.put("msg", "上傳成功");
map.put("data", entity);
return map;
}else{
return null;
}
}else{
return map;
}
}
/**
* 視頻文件類型判斷
*
* @param fileName
* @return
*/
private boolean checkFileType(String fileName) {
Iterator type = Arrays.asList(videoFiles).iterator();
while (type.hasNext()) {
String ext = type.next();
if (fileName.toLowerCase().endsWith(ext)) {
return true;
}
}
return false;
}
/**
* 圖片文件類型判斷
*
* @param fileName
* @return
*/
public boolean checkPhotoFileType(String fileName) {
Iterator type = Arrays.asList(photoFiles).iterator();
while (type.hasNext()) {
String ext = type.next();
if (fileName.toLowerCase().endsWith(ext)) {
return true;
}
}
return false;
}
/**
* 視頻類型判斷(flv)
*
* @param fileName
* @return
*/
private boolean checkMediaType(String fileEnd) {
Iterator type = Arrays.asList(allowFLV).iterator();
while (type.hasNext()) {
String ext = type.next();
if (fileEnd.equals(ext)) {
return true;
}
}
return false;
}
/**
* 視頻類型判斷(AVI)
*
* @param fileName
* @return
*/
private boolean checkAVIType(String fileEnd) {
Iterator type = Arrays.asList(allowAVI).iterator();
while (type.hasNext()) {
String ext = type.next();
if (fileEnd.equals(ext)) {
return true;
}
}
return false;
}
/**
* 獲取文件擴展名
*
* @return string
*/
private String getFileExt(String fileName) {
return fileName.substring(fileName.lastIndexOf("."));
}
/**
* 依據原始文件名生成新文件名
* @return
*/
private String getName(String fileName) {
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd_HH~mm~ss");
Iterator type = Arrays.asList(allowFiles).iterator();
while (type.hasNext()) {
String ext = type.next();
if (fileName.contains(ext)) {
String newFileName = formatter.format(date) + "_" + stringfilString(fileName.substring(0, fileName.lastIndexOf(ext)));
return newFileName;
}
}
return "";
}
public static String stringfilString(String str){
// 只允許字母和數字 // String regEx = "[^a-zA-Z0-9]";
// 清除掉所有特殊字符
String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\]<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
return filterChinese(m.replaceAll("").trim());
}
public static String filterChinese(String chin){
return chin.replaceAll("[\\u4e00-\\u9fa5]", "");
}
/**
* 文件大小,返回kb.mb
*
* @return
*/
private String getSize(File file) {
String size = "";
long fileLength = file.length();
DecimalFormat df = new DecimalFormat("#.00");
if (fileLength < 1024) {
size = df.format((double) fileLength) + "BT";
} else if (fileLength < 1048576) {
size = df.format((double) fileLength / 1024) + "KB";
} else if (fileLength < 1073741824) {
size = df.format((double) fileLength / 1048576) + "MB";
} else {
size = df.format((double) fileLength / 1073741824) + "GB";
}
return size;
}
}
3.實體類
public class FileEntity {
private String type;
private String size;
private String path;
private String titleOrig;
private String titleAlter;
private Timestamp uploadTime;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getTitleOrig() {
return titleOrig;
}
public void setTitleOrig(String titleOrig) {
this.titleOrig = titleOrig;
}
public String getTitleAlter() {
return titleAlter;
}
public void setTitleAlter(String titleAlter) {
this.titleAlter = titleAlter;
}
public Timestamp getUploadTime() {
return uploadTime;
}
public void setUploadTime(Timestamp uploadTime) {
this.uploadTime = uploadTime;
}
}
4.設置編碼格式
package com.test.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class TransfMediaTools {
/**
* 視頻轉碼flv
*
* @param ffmpegPath
* 轉碼工具的存放路徑
* @param upFilePath
* 用于指定要轉換格式的文件,要截圖的視頻源文件
* @param codcFilePath
* 格式轉換后的的文件保存路徑
* @return
* @throws Exception
*/
public void processFLV(String ffmpegPath, String upFilePath, String codcFilePath) {
// 創建一個List集合來保存轉換視頻文件為flv格式的命令
List convert = new ArrayList();
convert.add(ffmpegPath); // 添加轉換工具路徑
convert.add("-i"); // 添加參數"-i",該參數指定要轉換的文件
convert.add(upFilePath); // 添加要轉換格式的視頻文件的路徑
convert.add("-ab");
convert.add("56");
convert.add("-ar");
convert.add("22050");
convert.add("-q:a");
convert.add("8");
convert.add("-r");
convert.add("15");
convert.add("-s");
convert.add("600*500");
/*
* convert.add("-qscale"); // 指定轉換的質量 convert.add("6");
* convert.add("-ab"); // 設置音頻碼率 convert.add("64"); convert.add("-ac");
* // 設置聲道數 convert.add("2"); convert.add("-ar"); // 設置聲音的采樣頻率
* convert.add("22050"); convert.add("-r"); // 設置幀頻 convert.add("24");
* convert.add("-y"); // 添加參數"-y",該參數指定將覆蓋已存在的文件
*/
convert.add(codcFilePath);
try {
Process videoProcess = new ProcessBuilder(convert).redirectErrorStream(true).start();
new PrintStream(videoProcess.getInputStream()).start();
videoProcess.waitFor();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 對ffmpeg無法解析的文件格式(wmv9,rm,rmvb等), 先用mencoder轉換為avi(ffmpeg能解析的)格式
*
* @param mencoderPath
* 轉碼工具的存放路徑
* @param upFilePath
* 用于指定要轉換格式的文件,要截圖的視頻源文件
* @param codcFilePath
* 格式轉換后的的文件保存路徑
* @return
* @throws Exception
*/
public String processAVI(String mencoderPath, String upFilePath, String codcAviPath) {
// boolean flag = false;
List commend = new ArrayList();
commend.add(mencoderPath);
commend.add(upFilePath);
commend.add("-oac");
commend.add("mp3lame");
// commend.add("lavc");
commend.add("-lameopts");
commend.add("preset=64");
commend.add("-lavcopts");
commend.add("acodec=mp3:abitrate=64");
commend.add("-ovc");
commend.add("xvid");
commend.add("-xvidencopts");
commend.add("bitrate=600");
commend.add("-of");
commend.add("avi");
commend.add("-o");
commend.add(codcAviPath);
try {
// 預處理進程
ProcessBuilder builder = new ProcessBuilder();
builder.command(commend);
builder.redirectErrorStream(true);
// 進程信息輸出到控制臺
Process p = builder.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
p.waitFor();// 直到上面的命令執行完,才向下執行
return codcAviPath;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
class PrintStream extends Thread {
java.io.InputStream __is = null;
public PrintStream(java.io.InputStream is) {
__is = is;
}
public void run() {
try {
while (this != null) {
int _ch = __is.read();
if (_ch != -1)
System.out.print((char) _ch);
else
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
5.調用接口上傳
/**
* 上傳視頻
* @param file
* @param request
* @param model
* @param session
* @param response
* @return
*/
@RequestMapping("/uploadflv")
@ResponseBody
public Object uploadflv(@RequestParam("file") MultipartFile file, HttpServletRequest request, Model model, HttpSession session, HttpServletResponse response){
FileUploadTool fileUploadTool=new FileUploadTool();
Object map=fileUploadTool.createFile(file, request, session);
return map;
}
總結
以上是生活随笔為你收集整理的java mencoder_java 用ffmpeg和mencoder进行视频转码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python IDEL 快捷键
- 下一篇: 【工具封装】Python 实现将阿拉伯数