拆分
public static void cutVideo(File file, Integer max) {
//计算需要分成多少个视频
int num = file.length() / max;
try {
RandomAccessFile raf1 = new RandomAccessFile(file, "r");
// 每次取2M
byte[] bytes = new byte[2048];
int len = -1;
for (int i = 0; i < num; i++) {
String name = "partVideo" + i + ".mp4";
File file2 = new File(name);
RandomAccessFile raf2 = new RandomAccessFile(file2, "rw");
//读到文件末尾时,len返回-1,结束循环
while ((len = raf1.read(bytes)) != -1){
raf2.write(bytes, 0, len);
//当生成的新文件字节数大于lon时,结束循环
if (raf2.length() > lon)
break;
}
raf2.close();
}
raf1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
视频合并
public static void mergeVideo(List<File> file) {
File file = new File("...\\newVideo.mp4");
try {
RandomAccessFile target = new RandomAccessFile(file, "rw");
for (int i = 0; i < file.length(); i++) {
File file2 = file(i)
RandomAccessFile src = new RandomAccessFile(file2, "r");
//每次读取2M
byte[] bytes = new byte[2048];
int len = -1;
while ((len = src.read(bytes)) != -1) {
//循环赋值
target.write(bytes, 0, len);
}
src.close();
}
target.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
使用
以上方式拆分的视频和合并不同的视频所生成的新视频都只能播放第一段视频,可能是因为视频特有的头信息无法通过简单的流信息输入输出来进行转换,所有以上方法适合对一个容量视频进行网络传输时减少失败性。