前段時間,項目開發中有一個功能要實現在線播放視頻,對方要求支持所有格式,而在線播放的格式只有使用flash播放器支持的flv格式,於是只好想辦法實現其它視頻格式向flv視頻轉換的功能,現整理出來放在博客上,以便給和我有着一樣的需求的初學者一點參考。
本功能主要依賴ffmpeg和mencoder軟件才能使用。網上對ffmpeg和mencoder的參數詳細配置已經有了較爲詳細的描述,此處不再贅述;
下面直接上代碼:
package org.hubu.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class ConvertFlv03 {
private static String beginTime = "";
private static String endTime = "";
public static void main(String[] args) {
new Thread(// 每次啓動都創建一個新的Thread
new Runnable() {
public void run() {
ConvertFlv03.convert("K:\\111.flv", "K:\\convert555.flv");
};
}).start();
}
public static boolean convert(String inputFile, String outputFile) {
if (!checkfile(inputFile)) {
System.out.println(inputFile + " is not file");
return false;
}
if (process(inputFile, outputFile)) {
System.out.println("ok");
return true;
}
return false;
}
// 檢查文件是否存在
private static boolean checkfile(String path) {
File file = new File(path);
if (!file.isFile()) {
return false;
}
return true;
}
private static boolean process(String inputFile, String outputFile) {
int type = checkContentType(inputFile);
boolean status = false;
if (type == 0) {
status = processFLV(inputFile, outputFile);// 直接將文件轉爲flv文件
} else if (type == 1) {
String avifilepath = processAVI(type, inputFile);
if (avifilepath == null)
return false;// avi文件沒有得到
status = processFLV(avifilepath, outputFile);// 將avi轉爲flv
}
return status;
}
/**
* 檢查視頻類型
*
* @param inputFile
* @return ffmpeg 能解析返回0,不能解析返回1
*/
private static int checkContentType(String inputFile) {
String type = inputFile.substring(inputFile.lastIndexOf(".") + 1,
inputFile.length()).toLowerCase();
// ffmpeg能解析的格式:(asx,asf,mpg,wmv,3gp,mp4,mov,avi,flv等)
if (type.equals("avi")) {
return 0;
} else if (type.equals("mpg")) {
return 0;
} else if (type.equals("wmv")) {
return 0;
} else if (type.equals("3gp")) {
return 0;
} else if (type.equals("mov")) {
return 0;
} else if (type.equals("mp4")) {
return 0;
} else if (type.equals("asf")) {
return 0;
} else if (type.equals("asx")) {
return 0;
} else if (type.equals("flv")) {
return 0;
}
// 對ffmpeg無法解析的文件格式(wmv9,rm,rmvb等),
// 可以先用別的工具(mencoder)轉換爲avi(ffmpeg能解析的)格式.
else if (type.equals("wmv9")) {
return 1;
} else if (type.equals("rm")) {
return 1;
} else if (type.equals("rmvb")) {
return 1;
}
return 9;
}
/**
* ffmepg: 能解析的格式:(asx,asf,mpg,wmv,3gp,mp4,mov,avi,flv等)
*
* @param inputFile
* @param outputFile
* @return
*/
private static boolean processFLV(String inputFile, String outputFile) {
beginTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:ms")
.format(new Date());
if (!checkfile(inputFile)) {
System.out.println(inputFile + " is not file");
return false;
}
List<String> commend = new java.util.ArrayList<String>();
// 低精度
String path = System.getProperty("user.dir");
String ffmpegPath = path + "\\tools\\ffmpeg.exe";
commend.add(ffmpegPath);// 添加轉換工具路徑
commend.add("-i");// 添加參數"-i",該參數指定要轉換的文件
commend.add(inputFile);// 添加要轉換格式的視頻文件的路徑
commend.add("-ab");// 設置音頻碼率
commend.add("128");
commend.add("-acodec");
commend.add("libmp3lame");
commend.add("-ac");// 設置聲道數
commend.add("1");
commend.add("-ar");// 設置聲音的採樣頻率
commend.add("22050");
// commend.add("-qscale");//指定轉換的質量,以<數值>質量爲基礎的VBR,取值0.01-255,約小質量越好
// commend.add("8");
commend.add("-s");// 設置幀大小,格式爲WXH,缺省160X128
commend.add("1324x768");// 表示設置目標視頻文件的分辨率//這裏爲標清
commend.add("-r");// 設置幀頻
commend.add("29.97");
commend.add("-b");// 設置比特率,缺省200kb/s
commend.add("500");
commend.add("-y");// 添加參數"-y",該參數指定將覆蓋已存在的文件
commend.add(outputFile);
try {
ProcessBuilder builder = new ProcessBuilder();
builder.command(commend);
Process p = builder.start();
doWaitFor(p);
new File(inputFile).delete();// 轉換完成刪除緩存文件
endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:ms")
.format(new Date());
System.out.println("我是flv轉換的開始時間爲:" + beginTime
+ "\n我是flv轉換的結束時間爲:" + endTime);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* Mencoder: 對ffmpeg無法解析的文件格式(wmv9,rm,rmvb等),
* 可以先用別的工具(mencoder)轉換爲avi(ffmpeg能解析的)格式.
*
* @param type
* @param inputFile
* @return
*/
private static String processAVI(int type, String inputFile) {
beginTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:ms")
.format(new Date());
System.out.println("我是 processAVI進程");
// File file =new File("D://temp.avi");
// if(file.exists()) file.delete();
String fileTempName = "D:\\"
+ new SimpleDateFormat("yyMMddHHmmssssss").format(new Date())
+ "." + "avi";
List<String> commend = new java.util.ArrayList<String>();
String path = System.getProperty("user.dir");
String mencoderPath = path + "\\tools\\mencoder.exe";
commend.add(mencoderPath);
commend.add(inputFile);
commend.add("-oac");
commend.add("mp3lame");
commend.add("-lameopts");
commend.add("preset=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(fileTempName);
StringBuffer test = new StringBuffer();
for (int i = 0; i < commend.size(); i++)
test.append(commend.get(i) + " ");
System.out.println(test);
try {
ProcessBuilder builder = new ProcessBuilder();
builder.command(commend);
Process p = builder.start();
/**
* 清空Mencoder進程 的輸出流和錯誤流 因爲有些本機平臺僅針對標準輸入和輸出流提供有限的緩衝區大小,
* 如果讀寫子進程的輸出流或輸入流迅速出現失敗,則可能導致子進程阻塞,甚至產生死鎖。
*/
final InputStream is1 = p.getInputStream();
final InputStream is2 = p.getErrorStream();
new Thread() {
public void run() {
BufferedReader br = new BufferedReader(
new InputStreamReader(is1));
try {
String lineB = null;
while ((lineB = br.readLine()) != null) {
if (lineB != null)
System.out.println(lineB);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
new Thread() {
public void run() {
BufferedReader br2 = new BufferedReader(
new InputStreamReader(is2));
try {
String lineC = null;
while ((lineC = br2.readLine()) != null) {
if (lineC != null)
System.out.println(lineC);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
p.waitFor();
new File(inputFile).delete();// 轉換完成刪除緩存文件
endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:ms")
.format(new Date());
System.out.println("avi進程的開始時間:" + beginTime + "\n avi進程的結束時間"
+ endTime);
System.out.println("avi 轉換進程完成 finish");
return fileTempName;
} catch (Exception e) {
System.err.println(e);
return null;
}
}
public static int doWaitFor(Process p) {
InputStream in = null;
InputStream err = null;
int exitValue = -1; // returned to caller when p is finished
try {
System.out.println("comeing");
in = p.getInputStream();
err = p.getErrorStream();
boolean finished = false; // Set to true when p is finished
while (!finished) {
try {
while (in.available() > 0) {
Character c = new Character((char) in.read());
System.out.print(c);
}
while (err.available() > 0) {
Character c = new Character((char) err.read());
System.out.print(c);
}
exitValue = p.exitValue();
finished = true;
} catch (IllegalThreadStateException e) {
Thread.currentThread().sleep(500);
}
}
} catch (Exception e) {
System.err.println("doWaitFor();: unexpected exception - "
+ e.getMessage());
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
if (err != null) {
try {
err.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
return exitValue;
}
}
代碼中用到了兩個工具,分別是ffmpeg.exe和mencoder.exe兩個軟件,我在此次代碼實例中,將兩個組件放在了新建文件夾下了如下圖所示:
至此便實現了將asx,asf,mpg,wmv,3gp,mp4,mov,avi,flv,wmv9,rm,rmvb等視頻格式向flv視頻格式的轉換。