文件上传时进行合块时,代码运行正常,也合出了一个符合预期的文件,但是点击却无法播放
//测试文件合块方法
@Test
public void mergeChunk() throws Exception {
//指定块文件所在目录
String chunkFileDirPath = "D:\\ffmpeg-vedio\\chunk\\";
File chunkDirFile = new File(chunkFileDirPath);
//获取块文件列表信息
File[] files = chunkDirFile.listFiles();
//指定合并文件所在路径
String mergeFilePath = "D:\\ffmpeg-vedio\\bys.mp4";
File mergeFile = new File(mergeFilePath);
//创建输出流
RandomAccessFile rw = new RandomAccessFile(mergeFile, "rw");
rw.seek(0);//强制从参数为止开始写
//创建缓冲区
byte[] bytes = new byte[1024];
int len = -1;
//遍历块文件,写入输出流
for (File file : files) {
//创建输入流
RandomAccessFile r = new RandomAccessFile(file, "r");
while ((len = r.read(bytes)) != -1) {
rw.write(bytes, 0, len);
}
r.close();
}
rw.close();
}

原因:分块时文件名为数字,合块时顺序为0,1,10(超过10块)
合成顺序与分块顺序不同
解决方法:
1.通过Arrays工具类转化为list集合,先进行排序后再合块
//测试文件合块方法
@Test
public void mergeChunk1() throws Exception {
//指定块文件所在目录
String chunkFileDirPath = "D:\\ffmpeg-vedio\\chunk\\";
File chunkDirFile = new File(chunkFileDirPath);
//获取块文件列表信息
File[] files = chunkDirFile.listFiles();
List<File> fileList = Arrays.asList(files);
fileList.sort(new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
if(Integer.parseInt(o1.getName())>Integer.parseInt(o2.getName())){
return 1;
}else{
return -1;
}
}
});
//指定合并文件所在路径
String mergeFilePath = "D:\\ffmpeg-vedio\\bys.mp4";
File mergeFile = new File(mergeFilePath);
//创建输出流
RandomAccessFile rw = new RandomAccessFile(mergeFile, "rw");
rw.seek(0);//强制从参数为止开始写
//创建缓冲区
byte[] bytes = new byte[1024];
int len = -1;
//遍历块文件,写入输出流
for (File file : fileList) {
//创建输入流
RandomAccessFile r = new RandomAccessFile(file, "r");
while ((len = r.read(bytes)) != -1) {
rw.write(bytes, 0, len);
}
r.close();
}
rw.close();
}
2.for循环中自己重新定义一个file
@Test
public void mergeChunk2() throws Exception {
//指定块文件所在目录
String chunkFileDirPath = "D:\\ffmpeg-vedio\\chunk\\";
File chunkDirFile = new File(chunkFileDirPath);
//获取块文件列表信息
File[] files = chunkDirFile.listFiles();
//指定合并文件所在路径
String mergeFilePath = "D:\\ffmpeg-vedio\\bys.mp4";
File mergeFile = new File(mergeFilePath);
//创建输出流
RandomAccessFile rw = new RandomAccessFile(mergeFile, "rw");
rw.seek(0);//强制从参数为止开始写
//创建缓冲区
byte[] bytes = new byte[1024];
int len = -1;
//遍历块文件,写入输出流
for (int i = 0; i < files.length; i++) {
File file = new File(chunkFileDirPath + i);
//创建输入流
RandomAccessFile r = new RandomAccessFile(file, "r");
while ((len = r.read(bytes)) != -1) {
rw.write(bytes, 0, len);
}
r.close();
}
rw.close();
}
本文介绍了如何解决在合并分块视频时,由于文件名顺序导致播放失败的问题。作者提供了两种解决方案:一是使用Arrays工具对文件进行排序,二是重新定义for循环中的文件引用,确保合块操作按照正确的顺序进行。
508

被折叠的 条评论
为什么被折叠?



