附上java代码,可直接使用。使用前需要先将FFmpeg的bin目录配置在环境变量中。配置完成后,在cmd中拼 ffmpeg -version
如果能ping通说明配置成功,然后直接使用以下代码即可成功。
package com.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
* 视频中获取音频文件
*/
public class VideoUtils {
//FFmpeg全路径
private static final String FFMPEG_PATH = "D:666ffmpeg-20190730-a0c1970-win64-staticbinffmpeg.exe";
//音频保存路径
private static final String TMP_PATH = "D:666";
/**
* 从视频中提取音频信息
* @param videoUrl
* @return
*/
public static String videoToAudio(String videoUrl){
String aacFile = "";
try {
aacFile = TMP_PATH + "/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
+ UUID.randomUUID().toString().replaceAll("-", "") + ".mp3";
String command = FFMPEG_PATH + " -i "+ videoUrl + " -vn -acodec copy "+ aacFile;
System.out.println("video to audio command : " + command);
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static void main(String[] args){
try {
// videoToAudio("D:laji2.mp4");
String videoInputPath = "D:lajiaa.mp4";
String audioInputPath = "D:lajia.mp3";
String videoOutPath = "D:lajibb1.avi";
convetor(videoInputPath,audioInputPath,videoOutPath);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("---------获取音频文件成功!-----------");
}
/**
* @param videoInputPath 原视频的全路径
* @param audioInputPath 音频的全路径
* @param videoOutPath 视频与音频结合之后的视频的路径
* @throws Exception
*/
public static void convetor(String videoInputPath, String audioInputPath, String videoOutPath)
throws Exception {
Process process = null;
try {
String command =FFMPEG_PATH + " -i " + videoInputPath + " -i " + audioInputPath + " -c:v copy -c:a aac -strict experimental " +
" -map 0:v:0 -map 1:a:0 "
+ " -y " + videoOutPath;
process = Runtime.getRuntime().exec(command);
process.waitFor();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 使用这种方式会在瞬间大量消耗CPU和内存等系统资源,所以这里我们需要对流进行处理
InputStream errorStream = process.getErrorStream();
InputStreamReader inputStreamReader = new InputStreamReader(errorStream);
BufferedReader br = new BufferedReader(inputStreamReader);
String line = "";
while ((line = br.readLine()) != null) {
}
if (br != null) {
br.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (errorStream != null) {
errorStream.close();
}
}
}










