/**
* 合并音频文件
* @param videoPath 音频片段路径集合
* @param resultPath 生成文件路径
* @param isAdd 追加or覆盖
*
*/
public static void mergeMP3Files(List<String> videoPath, String resultPath, boolean isAdd){
File file = new File(resultPath);
if (file.exists()) {
file.delete();
}
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
try {
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(resultPath, isAdd), 1024 * 200);
for (int i = 0; i < videoPath.size(); i++) {
writeVideoFile(videoPath.get(i),outputStream);
}
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* @param videoPath 音频片段路径
* @param outputStream 音频流
*/
public static void writeVideoFile(String videoPath, BufferedOutputStream outputStream){
try {
MediaExtractor extractor = new MediaExtractor();
extractor.setDataSource(videoPath);
int videoTrackIndex = getAudioTrack(extractor);
if (videoTrackIndex < 0) {
return ;
}
//选择音频轨道
extractor.selectTrack(videoTrackIndex);
MediaFormat mediaFormat = extractor.getTrackFormat(videoTrackIndex);
//获取音频时间
float time = mediaFormat.getLong(MediaFormat.KEY_DURATION) / 1000;//返回的是微秒,转换成毫秒
//合并音频
ByteBuffer buffer = ByteBuffer.allocate(1024 * 200);
while (true) {
int sampleSize = extractor.readSampleData(buffer, 0);
if (sampleSize <= 0) {
break;
}
byte[] buf = new byte[sampleSize];
buffer.get(buf, 0, sampleSize);
//写入文件
outputStream.write(buf);
//音轨数据往前读
extractor.advance();
}
extractor.release();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取音频数据轨道
*/
private static int getAudioTrack(MediaExtractor extractor) {
for (int i = 0; i < extractor.getTrackCount(); i++) {
MediaFormat format = extractor.getTrackFormat(i);
String mime = format.getString(MediaFormat.KEY_MIME);
if (mime.startsWith("audio")) {//audio为音频,video为视频
return i;
}
}
return -1;
}
记录一下