您的位置:首页 > 其它

转换音频和视频ffmpeg

2018-01-04 18:19 393 查看
使用之前先把
ffmpeg包放入工程的下。确保编译后在classes层,这里有我写的MP3到ogg,ogg到MP3,语音信息获取等

package xx.util;

import xx.ParameterChecker;
import xx.StringUtilsEx;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FFMpegUtils {

/**
* ffmpeg 目录路径
*/
private final static String FFMPEG_PATH = "files/ffmpeg/";

private static String ffmpegUri ;

private static String mencoderUri;

/**
* 初始化 ffmpeg路径
*/
private static void init(){
if(ffmpegUri==null){
Properties prop = System.getProperties();
String os = prop.getProperty("os.name");
String realPath=StringUtilsEx.getContextPath();
if(os.startsWith("win") || os.startsWith("Win")){
ffmpegUri = realPath + FFMPEG_PATH + "windows/ffmpeg.exe";
mencoderUri = realPath + FFMPEG_PATH + "windows/mencoder.exe";
}
else{
ffmpegUri = realPath + FFMPEG_PATH + "linux/ffmpeg";
mencoderUri = realPath + FFMPEG_PATH + "linux/mencoder";
}
}
}

private static String getFfmpegUri(){
init();
return ffmpegUri;
}

private static String getMencoderUri(){
init();
return mencoderUri;
}

/**
* 获取音频信息
* @param filePath 源文件路径
*/
public static Audio parseAudio(String filePath)throws Exception{
List<String> cmd = new ArrayList<String>();
cmd.add(getFfmpegUri());
cmd.ad
1fa48
d("-i");
cmd.add(filePath);
Audio audio = new Audio();
try{
String result = exec(cmd);
if(ParameterChecker.isNullOrEmpty(result)){
System.out.println("视频文件解析失败");
}
Matcher matcherInput = Pattern.compile("Input #0, (.*?), from (.*?)").matcher(result);
Matcher baseMatcher  = Pattern.compile("Duration: (.*?),(.*?)bitrate: (\\d*) kb\\/s").matcher(result);
Matcher audioMatcher = Pattern.compile("Audio: (\\w*)(.*?), (\\d*) Hz").matcher(result);
if(matcherInput.find()){
audio.setType(matcherInput.group(1));
}
if(baseMatcher.find()){
audio.setDuration( runtimeToSecond(baseMatcher.group(1)));
audio.setBitRate(Long.parseLong(baseMatcher.group(3)));
}
if(audioMatcher.find()){
audio.setFormat(audioMatcher.group(1));
audio.setFrequency(audioMatcher.group(3));
}

}
catch(Exception ex){
System.out.println("视频文件解析失败");
}

return audio;
}

/**
* 获取视频信息
* @param filePath 源文件路径
*/
public static Video parseVideo(String filePath)throws Exception{
List<String> cmd = new ArrayList<String>();
cmd.add(getFfmpegUri());
cmd.add("-i");
cmd.add(filePath);
Video video = new Video();
try{
video.setSrcFile(filePath);
String result = exec(cmd);
if(ParameterChecker.isNullOrEmpty(result)){
System.out.println("视频文件解析失败");
}

Matcher matcherInput = Pattern.compile("Input #0, (.*?), from (.*?)").matcher(result);
Matcher baseMatcher  = Pattern.compile("Duration: (.*?), start: (.*?), bitrate: (\\d*) kb\\/s").matcher(result);
Matcher videoMatcher = Pattern.compile("Video: (\\w*)(.*?), (.*?), (.*?)[\\s\\S]*").matcher(result);
Matcher audioMatcher = Pattern.compile("Audio: (\\w*)(.*?), (\\d*) Hz").matcher(result);
Matcher rotateMatcher = Pattern.compile("rotate(\\s*):(\\s*)(\\d+)").matcher(result);
if(matcherInput.find()){
video.setType(matcherInput.group(1));
}
if(baseMatcher.find()){
video.setDuration( runtimeToSecond(baseMatcher.group(1)));
video.setBitRate(Integer.parseInt(baseMatcher.group(3)));
}
if(rotateMatcher.find()){
int rotate = Integer.parseInt(rotateMatcher.group(3));
video.setRotate((rotate+360) % 360);
}
if(videoMatcher.find()){
String videoInfo = videoMatcher.group(0);
Matcher m = Pattern.compile("([1-9]\\d*x[1-9]\\d*)").matcher(videoInfo);
if(m.find()){
video.setResolution(m.group(0));
video.setDestResolution();
}
m = Pattern.compile("Unknown format").matcher(videoInfo);
if(m.find()){
video.setSupport(false);
}
else{
video.setSupport(true);
}
video.setVideoFormat(videoMatcher.group(1));
}
if(audioMatcher.find()){
video.setAudioFormat(audioMatcher.group(1));
}

}
catch(Exception ex){
System.out.println("视频文件解析失败");
}
return video;
}

public static Process processAvi(String originFileUri , String fileSavePath) throws Exception {
List<String> commend = new ArrayList<String>();
commend.add(getMencoderUri());
commend.add(originFileUri);
commend.add("-ovc");
commend.add("lavc");
commend.add("-oac");
commend.add("mp3lame");
commend.add("-lavcopts");
commend.add("acodec=mp3:abitrate=64");
commend.add("-xvidencopts");
commend.add("bitrate=600");
commend.add("-vf");
commend.add("scale=320:-3");
commend.add("-of");
commend.add("avi");
commend.add("-o");
commend.add(fileSavePath);

ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command(commend);
Process p = processBuilder.start();
return p;
}

public static void audioTransOgg(String originFileUri, String fileSavePath) throws Exception {
try {
List<String> commend = new ArrayList<String>();
commend.add(getFfmpegUri());
commend.add("-i");
commend.add(originFileUri);
commend.add("-acodec");
commend.add("libvorbis");
commend.add(fileSavePath);
exec(commend);
}
catch(Exception ex){
System.out.println("视频文件解析失败");
}
}

/**
* 生成视频截图
* @param filePath 源文件路径
* @param imageSavePath 截图文件保存全路径
* @param screenSize 截图大小 如640x480
* @param transpose 旋转
*/
public static void makeScreenCut( String filePath, String imageSavePath , String screenSize ,String transpose )throws Exception{
try{
List<String> cmd = new ArrayList<String>();
cmd.add(getFfmpegUri());
cmd.add("-i");
cmd.add(filePath);
cmd.add("-y");
cmd.add("-f");
cmd.add("image2");
cmd.add("-ss");
cmd.add("1");
cmd.add("-t");
cmd.add("0.001");
if(!ParameterChecker.isNullOrEmpty(transpose)){
cmd.add("-vf");
cmd.add(transpose);
}
cmd.add("-s");
cmd.add(screenSize);
cmd.add(imageSavePath);

exec(cmd);
}
catch(Exception ex){
System.out.println("视频文件解析失败");
}
}

/**
* 音频转换
* @param filePath 源文件路径
* @param fileSavePath 文件保存全路径
* @param audioByte 音频比特率
* @param audioCollection 音频采样率
* @param fps 每秒帧数(15或29.97)
*/
public static void audioTransfer(String filePath, String fileSavePath,  int audioByte, int audioCollection)throws Exception{
try{
List<String> cmd = new ArrayList<String>();
cmd.add(getFfmpegUri());
cmd.add("-i");
cmd.add(filePath);
cmd.add("-y");
cmd.add("-ab");
cmd.add( Integer.toString(audioByte) );
cmd.add("-ar");
cmd.add( Integer.toString(audioCollection) );
cmd.add("-ac");
cmd.add("1");
cmd.add( fileSavePath );
exec(cmd);
}
catch(Exception ex){
System.out.println("视频文件解析失败");
}
}

/**
* 视频转换(转为libxvid)
* @param filePath 源文件路径
*/
public static String toLibxvid(String filePath) throws Exception{
try{
String ext = getFileExtention(filePath);
String fileSavePath = filePath.replace("." + ext, ".tmp."+ext );
List<String> cmd = new ArrayList<String>();
cmd.add(getFfmpegUri());
cmd.add("-i");
cmd.add(filePath);
cmd.add("-y");
cmd.add("-c:v");
cmd.add("libxvid");
cmd.add( fileSavePath );
exec(cmd);
return fileSavePath;
}
catch(Exception ex){
System.out.println("视频转换失败");
return null;
}
}

/**
* 视频转换
* @param filePath 源文件路径
* @param fileSavePath 文件保存全路径
* @param screenSize 视频分辨率 如640x480
* @param audioByte 音频比特率
* @param audioCollection 音频采样率
* @param quality 视频质量(1-51)越低质量越好( 默认23)
* @param preset (压制速度placebo<veryslow<slower<slow<medium<fast<faster<veryfast<superfast<ultrafast) 默认medium,压缩率与速度成反比
* @param fps 每秒帧数(15或29.97)
* @param transpose 旋转
*
*
*/
public static void videoTransfer(String filePath, String fileSavePath, String screenSize, int audioByte, int audioCollection, double quality, String preset,  double fps, String transpose)throws Exception{
try{
List<String> cmd = new ArrayList<String>();
cmd.add(getFfmpegUri());
cmd.add("-i");
cmd.add(filePath);
cmd.add("-y");
cmd.add("-ab");
cmd.add( Integer.toString(audioByte) );
cmd.add("-ar");
cmd.add( Integer.toString(audioCollection) );
cmd.add("-r");
cmd.add( Double.toString(fps) );
cmd.add("-crf");
cmd.add( Double.toString(quality) );
cmd.add("-preset");
cmd.add(preset);
cmd.add("-profile:v");
cmd.add("baseline");
if(!ParameterChecker.isNullOrEmpty(transpose)){
cmd.add("-vf");
cmd.add(transpose);
cmd.add("-metadata:s:v:0");
cmd.add("rotate=0");
}
cmd.add("-s");
cmd.add(screenSize);
cmd.add( fileSavePath );
exec(cmd);
}
catch(Exception ex){
System.out.println("视频转换失败");
}
}

/**
*
* @param filePath
* @param fileSavePath
* @param screenSize
* @param transpose
*/
public static void videoTransfer(String filePath, String fileSavePath, String screenSize, String transpose) throws Exception{
videoTransfer(filePath, fileSavePath, screenSize, 43000, 44100, 23, "medium", 15, transpose);
}

/**
* 把 hh:mm:ss 转为秒
* @param str
* @return
*/
private static int runtimeToSecond(String str){
int second = 0;
String[] s = str.split(":");
if(s.length == 3){
second = Integer.parseInt(s[0])*60*60 + Integer.parseInt(s[1])*60 + (int)Math.abs(Double.parseDouble(s[2]));
if (second == 0) {
second = 1;
}
}
return second;
}

/**
* 执行指令
* @param cmd 执行指令
* @throws Exception
*/
private static String exec( List<String> cmd) throws Exception{
String outPut = "";
ProcessBuilder builder = new ProcessBuilder();
builder.command(cmd);
builder.redirectErrorStream(true);
Process proc = builder.start();
BufferedReader stdout = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line;
while ((line = stdout.readLine()) != null) {
outPut += "\n" + line;
if(line.indexOf("Error") == 0){
System.out.println(line);
}
}
proc.waitFor();
stdout.close();
String lastLine = outPut.substring(outPut.lastIndexOf("\n")+1);
if(lastLine.indexOf("Error") == 0){
throw new Exception(lastLine);
}
return outPut;
}

/**
* 校验文件是否是语音
* @param filePath
* @return
*/
public static boolean checkIsAudio(String filePath)throws Exception{
Audio audio = parseAudio(filePath);
if(audio.getType()!=null){
String[] formats = {"mp3", "wma", "wav", "amr", "asf"};
for(String format : formats){
if(audio.getType().indexOf(format) > -1){
return true;
}
else if(audio.getFormat() != null && audio.getFormat().indexOf("wmav2") > -1){
return true;
}
}
}
return false;
}

/**
* 校验文件是否是视频
* @param filePath
* @return
*/
public static boolean checkIsVideo(String filePath)throws Exception{
Video video = FFMpegUtils.parseVideo(filePath);
if(video.getType()!=null){
String[] formats = {"rm", "rmvb", "wmv", "avi", "mpg", "mpeg", "mp4"};
for(String format : formats){
if(video.getType().indexOf(format) > -1 || video.getVideoFormat().indexOf(format) > -1){
return true;
}
}
}
return false;
}

/**
* 获取文件后缀
*/
public static String getFileExtention(String fileName) {
int pos = fileName.lastIndexOf(".");
if (pos > -1 && pos < fileName.length()) {
return fileName.substring(pos + 1);
}
return "";

}

public static void main(String args[]){
try {
//          FFMpegUtils.audioTransOgg("F:\\xxx\\xfasfasfffffffff.mp3", "F:\\xxx\\xfasfasfffffffff.ogg");
Audio audio=FFMpegUtils.parseAudio("F:\\xxx\\xfasfasfffffffff.ogg");
FFMpegUtils.audioTransfer("F:\\xxx\\xfasfasfffffffff.ogg", "F:\\xxx\\xfasfasfffffffff.mp3",Integer.valueOf(audio.getBitRate()+""),Integer.valueOf(audio.getFrequency()));
}catch (Exception e){
System.out.println(e);
}
}
}

package xx.util;

public class Video {

public static final int WIDTH = 320;

public static final int HEIGHT = 240;

public static final String DEFAULT_RESOLUTION = "320*240";

public static final double RATE = (double) WIDTH / HEIGHT;

/**
* 1M
*/
public static final int MAX_SIZE = 1024 * 1024 ;

/**
* 时长
*/
private long duration;

/**
* 码率 比特率
*/
private long bitRate;

/**
* 分辨率
* @return
*/
private String resolution;

/**
* 宽
*/
private int width = WIDTH;

/**
* 高
*/
private int height = HEIGHT;

/**
* 源路径
*/
private String srcFile;

/**
* 目标路径
*/
private String destFile;

/**
* 类型
*/
private String type;

/**
* 视频格式
*/
private String videoFormat;

/**
* 音频格式
*/
private String audioFormat;

/**
* 封面
*/
private String frontCover;

/**
* 旋转角度
*/
private int rotate;

/**
* 旋转
*/
private String transpose;

/**
* 是否可识别
* @return
*/
private boolean support;

public long getDuration() {
return duration;
}

public void setDuration(long duration) {
this.duration = duration;
}

public long getBitRate() {
return bitRate;
}

public void setBitRate(long bitRate) {
this.bitRate = bitRate;
}

public String getResolution() {
return resolution;
}

public void setResolution(String resolution) {
this.resolution = resolution;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public String getVideoFormat() {
return videoFormat;
}

public void setVideoFormat(String videoFormat) {
this.videoFormat = videoFormat;
}

public String getAudioFormat() {
return audioFormat;
}

public void setAudioFormat(String audioFormat) {
this.audioFormat = audioFormat;
}

public boolean isSupport() {
return support;
}

public void setSupport(boolean support) {
this.support = support;
}

public String getFrontCover() {
return frontCover;
}

public void setFrontCover(String frontCover) {
this.frontCover = frontCover;
}

public int getWidth() {
return width;
}

public void setWidth(int width) {
this.width = width;
}

public int getHeight() {
return height;
}

public void setHeight(int height) {
this.height = height;
}

public String getSrcFile() {
return srcFile;
}

public void setSrcFile(String srcFile) {
this.srcFile = srcFile;
}

public String getDestFile() {
return destFile;
}

public void setDestFile(String destFile) {
this.destFile = destFile;
}

/**
* 获取视频分辨率
*/
public void setDestResolution(){
this.width = WIDTH;
this.height = HEIGHT;
String resolution  = this.getResolution();
if(resolution!=null && (resolution.indexOf("x")>0 ||resolution.indexOf("*")>0) ){
String sep = resolution.indexOf("x")>0 ? "x" : "*";
String[] nums = resolution.split(sep);
if(nums.length == 2){
int sWidth = Integer.parseInt(nums[0].trim());
int sHeight = Integer.parseInt(nums[1].trim());
double sRate = (double) sWidth / sHeight;
this.width = sWidth;
this.height = sHeight;
if(sWidth >= sHeight){
if(sRate > RATE && sWidth > WIDTH){
this.width = WIDTH;
this.height = this.width * sHeight / sWidth;
}
else if(sRate <= RATE && sHeight > HEIGHT){
this.height = HEIGHT;
this.width = this.height * sWidth / sHeight;
}
}
else{
if(1/sRate > RATE && sHeight > WIDTH){
this.height = WIDTH;
this.width = this.height * sWidth / sHeight;
}
else if(1/sRate <= RATE && sWidth > HEIGHT){
this.width = HEIGHT;
this.height = this.width * sHeight / sWidth;
}
}

if(this.width % 2 !=0){
this.width +=1;
}
if(this.height % 2 !=0){
this.height +=1;
}

}
}
if(this.getRotate()==90 || this.getRotate() == 270){
int tmp = this.width;
this.width = this.height;
this.height = tmp;
}
}

/**
* 获取封面长宽比例
*/
public String getCoverResolution(){
int coverHeight = this.height > HEIGHT ? HEIGHT : this.height;
int coverWidth = coverHeight * this.getWidth() / this.getHeight();
return coverWidth + "*" + coverHeight;
}

/**
* 获取视频压缩长宽比
*/
public String getDestResolution(){
return this.getWidth() + "*" + this.getHeight();
}

public String getTranspose() {
return transpose;
}

public void setTranspose(String transpose) {
this.transpose = transpose;
}

public int getRotate() {
return rotate;
}

public void setRotate(int rotate) {
this.rotate = rotate;

switch (rotate) {
case 90:
this.setTranspose("transpose=1");
break;
case 180:
this.setTranspose("transpose=2,transpose=2");
break;
case 270:
this.setTranspose("transpose=2");
break;
}
}
}
package xx.util;
/**
* 音频
* @author Rubekid
*
*/
public class Audio {

/**
* 时长
*/
private long duration;

/**
* 码率 比特率
*/
private long bitRate;

public long getDuration() {
return duration;
}

/**
* 类型
*/
private String type;

/**
* 格式
*/
private String format;

/**
* 音频频率
*/
private String frequency;

public void setDuration(long duration) {
this.duration = duration;
}

public long getBitRate() {
return bitRate;
}

public void setBitRate(long bitRate) {
this.bitRate = bitRate;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public String getFormat() {
return format;
}

public void setFormat(String format) {
this.format = format;
}

public String getFrequency() {
return frequency;
}

public void setFrequency(String frequency) {
this.frequency = frequency;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐