我正试图使用ffmpeg将一个字节数组导出到视频文件中,但与我共事的人坚持要求我在参数中使用-vcodec copy
。然而,这会导致代码挂起,而如果我不使用-vcodec副本,代码就不会挂起。我不知道问题出在哪里,在过去的两个小时里,我一直在尝试调试这段代码。
这是代码的相关部分。我在代码挂起的行的上方和下方添加了注释。有人能帮我吗?
// This is the tricky part. We need to build an ffmpeg process that
// takes input from stdin, and then plug Java into that.
ProcessBuilder ffmpegBuilder = new ProcessBuilder();
String[] cmd = {"ffmpeg", "-i", "-","-vcodec", "copy", directory
+ "/" + fileName};
StringBuilder combinedCmd = new StringBuilder();
for (String s : cmd) {
combinedCmd.append(s);
combinedCmd.append(" ");
}
mLogger.log(Level.INFO,"Final command is " + combinedCmd.toString());
ffmpegBuilder.command(cmd);
ffmpegBuilder.redirectErrorStream(true); // So that stdout and stderr go
// to the same stream.
byte[] dataToWrite = new byte[data.size()];
for (int i = 0; i < dataToWrite.length; i++) {
dataToWrite[i] = data.get(i); // Is there really STILL no better way
// to convert an ArrayList to an
// array?!
}
try {
Process ffmpeg = ffmpegBuilder.start();
OutputStream stdin = ffmpeg.getOutputStream();
BufferedReader stdout = new BufferedReader(new InputStreamReader(
ffmpeg.getInputStream()));
//HANGS AT THIS LINE vvvvvvvvvvvvvvvv
stdin.write(dataToWrite);
//HANGS AT THIS LINE ^^^^^^^^^^^^^^^^
String line = "I know a song that gets on everybody's nerves...";
while ((line != null) && stdout.ready()) {
line = stdout.readLine();
mLogger.log(Level.INFO, line);
}
try {
ffmpeg.waitFor(2, TimeUnit.SECONDS);
ffmpeg.destroyForcibly();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
原来程序在写入数据的中途挂起了。那里有很多数据,我知道这一点有问题,所以我试图告诉java进程开始从我制作的BufferedReader读取stdout。这解决了问题。事实证明,BufferedReader已经满了,而且由于stdout无处可去,整个过程都挂起了。我在这里更改了挂在这个代码上的行:
for (int i = 0;i < dataToWrite.length;i++) {
stdin.write(dataToWrite[i]);
if (stdout.ready()) {
String line = stdout.readLine();
mLogger.log(Level.INFO, line);
}
}
这修复了一切。