FFmpegAudioCutterUtils.java
12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package com.bs.reception.utils;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: zhouhb
* @CreateTime: 2024-03-12 15:18
* @Description: ffmpeg 工具类
*/
@Slf4j
public class FFmpegAudioCutterUtils {
/**
* 使用FFmpeg根据时间戳切割音频文件。
*
* @param inputFile 需要切割的原始音频文件路径。
* @param outputFile 切割后的音频文件输出路径。
* @param startTime 切割开始的时间戳(单位:秒)。
* @param endTime 切割结束的时间戳(单位:秒)。 注意:startTime和endTime都应该是浮点数,表示秒数,可以有小数部分。
*/
public static void cutAudioByTimestamp(String inputFile, String outputFile, double startTime,
double endTime) {
try {
// 将时间戳转换为HH:MM:SS.ms格式
String startTimeStr = String.format("%02d:%02d:%02d.%03d", (int) (startTime / 3600),
(int) (startTime % 3600 / 60), (int) (startTime % 60), (int) ((startTime % 1) * 1000));
String endTimeStr = String.format("%02d:%02d:%02d.%03d", (int) (endTime / 3600),
(int) (endTime % 3600 / 60), (int) (endTime % 60), (int) ((endTime % 1) * 1000));
// 构造FFmpeg命令
String commandprefix = ffmpegCmd();
String[] cmdArray = new String[]{
commandprefix,
"-i", inputFile,
"-ss", startTimeStr,
"-to", endTimeStr,
"-c", "copy",
outputFile
};
ProcessBuilder pb = new ProcessBuilder(cmdArray);
pb.redirectErrorStream(true);
Process process = pb.start();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
log.info(line);
}
}
int exitCode = process.waitFor();
if (exitCode == 0) {
log.info("音频文件按照时间戳切割成功,输出文件: " + outputFile);
} else {
log.info("音频文件切割失败,FFmpeg退出代码: " + exitCode);
}
} catch (IOException e) {
log.error("Error executing command: " + e);
throw new RuntimeException(e);
} catch (InterruptedException e) {
log.error("Error executing command: " + e);
throw new RuntimeException(e);
}
}
/**
* 使用FFmpeg工具将两个音频文件合并为一个。
*
* @param inputFile1 第一个输入音频文件的路径。
* @param inputFile2 第二个输入音频文件的路径。
* @param outputFile 合并后输出音频文件的路径。
* @throws IOException 如果在执行命令行过程中发生IO异常。
* @throws InterruptedException 如果在等待命令行执行过程中被中断。
*/
public static void mergeAudio(String inputFile1, String inputFile2, String outputFile) {
try {
String commandprefix = ffmpegCmd();
List<String> cmdList = new ArrayList<>();
cmdList.add(commandprefix);
cmdList.add("-i");
cmdList.add(inputFile1);
cmdList.add("-i");
cmdList.add(inputFile2);
cmdList.add("-filter_complex");
cmdList.add("[0:a][1:a]concat=n=2:v=0:a=1[outa]");
cmdList.add("-map");
cmdList.add("[outa]");
cmdList.add(outputFile);
ProcessBuilder pb = new ProcessBuilder(cmdList);
pb.redirectErrorStream(true);
Process process = pb.start();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
log.info(line);
}
}
int exitCode = process.waitFor();
if (exitCode == 0) {
log.info("音频文件合并成功,输出文件:" + outputFile);
} else {
log.info("音频文件合并失败,退出码:" + exitCode);
}
} catch (IOException e) {
log.error("Error executing command: " + e);
throw new RuntimeException(e);
} catch (InterruptedException e) {
log.error("Error executing command: " + e);
throw new RuntimeException(e);
}
}
/**
* 使用FFmpeg工具将多个音频文件合并为一个。
*
* @param list 文件的路径j集合。
* @param outputFile 合并后输出音频文件的路径。
* @throws IOException 如果在执行命令行过程中发生IO异常。
* @throws InterruptedException 如果在等待命令行执行过程中被中断。
*/
public static void mergeAudioList(List<String> list, String outputFile) {
try {
String commandprefix = ffmpegCmd();
// 构建 FFmpeg 命令行参数
List<String> cmdList = new ArrayList<>();
cmdList.add(commandprefix);
for (String inputFile : list) {
cmdList.add("-i");
cmdList.add(inputFile);
}
cmdList.add("-filter_complex");
cmdList.add("concat=n=" + list.size() + ":v=0:a=1"); // 指定音频流合并,忽略视频流(假设录音文件只有音频)
cmdList.add(outputFile);
ProcessBuilder pb = new ProcessBuilder(cmdList);
pb.redirectErrorStream(true);
Process process = pb.start();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
log.info(line);
}
}
int exitCode = process.waitFor();
if (exitCode == 0) {
log.info("音频文件合并成功,输出文件:" + outputFile);
} else {
log.info("音频文件合并失败,退出码:" + exitCode);
}
} catch (IOException e) {
log.error("Error executing command: " + e);
throw new RuntimeException(e);
} catch (InterruptedException e) {
log.error("Error executing command: " + e);
throw new RuntimeException(e);
}
}
/**
* 计算输入音频文件的持续时间。
* 该方法通过调用ffprobe命令行工具来获取音频文件的持续时间,并将其转换为毫秒数返回。
*
* @param inputFile 音频文件的路径。
* @return 音频文件的持续时间,单位秒。如果无法获取持续时间或发生错误,则返回0。
*/
public static long duation(String inputFile) {
try {
String commandprefix = ffprobeCmd();
List<String> cmd = new ArrayList<>();
cmd.add(commandprefix);
cmd.add("-v");
cmd.add("error");
cmd.add("-show_entries");
cmd.add("format=duration");
cmd.add("-of");
cmd.add("default=noprint_wrappers=1:nokey=1");
cmd.add(inputFile);
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.redirectErrorStream(true);
Process process = pb.start();
StringBuilder output = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
output.append(line);
}
}
int exitCode = process.waitFor();
if (exitCode == 0) {
String out = output.toString().trim();
double seconds = Double.parseDouble(out);
return (long) Math.floor(seconds);
} else {
log.info("获取音频时长失败,退出码:" + exitCode);
}
} catch (Exception e) {
log.error("Error reading :" + e);
throw new RuntimeException(e);
}
return 0;
}
/**
* 使用ffmpeg工具转换音频文件格式。
*
* @param inputFile 需要转换的音频文件的路径
* @param outputFile 转换后音频文件的路径
* @throws RuntimeException 如果执行过程中发生IO异常或线程被中断
*/
public static void convertFormat(String inputFile, String outputFile) {
try {
String commandprefix = ffmpegCmd();
// 构建 FFmpeg 命令行参数
String[] cmdArray = new String[]{
commandprefix,
"-i", inputFile,
"-vn",
"-c:a", "libmp3lame",
"-qscale:a", "2",
outputFile
};
ProcessBuilder pb = new ProcessBuilder(cmdArray);
pb.redirectErrorStream(true);
Process process = pb.start();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
log.info(line);
}
}
int exitCode = process.waitFor();
if (exitCode == 0) {
log.info("音频文件转化成功,输出文件:" + outputFile);
} else {
log.info("音频文件转化失败,退出码:" + exitCode);
}
} catch (Exception e) {
log.error("Error msg :" + e);
throw new RuntimeException(e);
}
}
private static void readAndLogOutput(BufferedReader reader, String streamName) {
try {
String line;
while ((line = reader.readLine()) != null) {
log.info(streamName + ": " + line);
}
} catch (Exception e) {
log.info("Error reading " + streamName + ": " + e.getMessage());
}
}
// 判断当前系统是windows还是其他
public static boolean isWindows() {
return System.getProperty("os.name").toLowerCase().startsWith("win");
}
private static String ffmpegCmd() {
String env = System.getenv("FFMPEG_EXE");
if (env != null && !env.isBlank()) {
return env;
}
if (isWindows()) {
return "D:\\tools\\ffmpeg\\ffmpeg-8.0.1-essentials_build\\bin\\ffmpeg.exe";
}
return "ffmpeg";
}
private static String ffprobeCmd() {
String env = System.getenv("FFPROBE_EXE");
if (env != null && !env.isBlank()) {
return env;
}
if (isWindows()) {
return "D:\\tools\\ffmpeg\\ffmpeg-8.0.1-essentials_build\\bin\\ffprobe.exe";
}
return "ffprobe";
}
public static void main(String[] args) throws IOException, InterruptedException {
// 切割音频
/*cutAudioByTimestamp("F:\\360MoveData\\Users\\11\\Desktop\\test\\20240328_111725.aac",
"F:\\360MoveData\\Users\\11\\Desktop\\test\\test20240328.aac", 3782.0,4619.0);*/
/*convertFormat("F:\\360MoveData\\Users\\11\\Desktop\\test\\20240328_111725.aac","F:\\360MoveData\\Users\\11\\Desktop\\test\\20240328_111725aac.mp3");*/
/*
System.out.println(duation("F:\\360MoveData\\Users\\11\\Desktop\\test\\20240328_111725.aac"));
*/
// 合并音频
/* mergeAudio("F:\\360MoveData\\Users\\11\\Desktop\\test\\20240328_111725.aac",
"F:\\360MoveData\\Users\\11\\Desktop\\test\\nls-sample-16k.wav",
"F:\\360MoveData\\Users\\11\\Desktop\\test\\hebing.acc");*/
// List<String> list=new ArrayList<>();
// list.add("F:\\360MoveData\\Users\\11\\Desktop\\test\\20240328_111725.aac");
// list.add("F:\\360MoveData\\Users\\11\\Desktop\\test\\318402.aac");
// mergeAudioList(list, "F:\\360MoveData\\Users\\11\\Desktop\\test\\hebing2.aac");
System.out.println(isWindows());
}
}