我不知道如何在Java中启动一个进程来使用ffmpeg录制实况流。
我已经尝试了几种解决方案,但我当前的代码看起来像这样(简化):
public void startDownload() {
String[] processArgs = new String[] {
"ffmpeg",
"-i",
"https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8",
"-c",
"copy",
"-bsf:a",
"aac_adtstoasc",
"C:\\temp\\test.mp4"
};
ProcessBuilder processBuilder = new ProcessBuilder(processArgs);
try {
process = processBuilder.start();
process.wairFor(); // Do I need this? Actually the stream is running forever until I stop it manually.
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = br.readLine()) != null) { // this blocks forever
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}问题是,有些东西阻止了这个过程的启动。在本例中,br.readLine()将永远阻塞它,并且我无法从该进程中获得任何输出。
但在Intellij中终止jar /停止启动配置后,进程开始工作,我必须通过任务管理器终止它。
顺便说一句,运行一个不记录实况流的进程,就像执行ffmpeg一样。
我用的是Windows,jdk14,IntelliJ。
发布于 2020-05-27 16:23:32
我自己就能弄明白。您必须将输入流和输出流都通过管道传输到BufferedReader,并且需要读取它的所有行。
我的代码目前看起来像这样:
public void startDownload() {
String[] processArgs = new String[] {
"ffmpeg",
"-i",
"https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8",
"-c",
"copy",
"-bsf:a",
"aac_adtstoasc",
"C:\\temp\\test.mp4"
};
ProcessBuilder processBuilder = new ProcessBuilder(processArgs);
process = processBuilder.start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line = "";
String newLineCharacter = System.getProperty("line.separator");
boolean isOutReady = false;
boolean isErrorReady = false;
boolean isErrorOut = true;
boolean isErrorError = true;
boolean isPrintToConsole = false;
while (process.isAlive()) {
do {
isOutReady = stdInput.ready();
isErrorOut = true;
isErrorError = true;
if (isOutReady) {
line = stdInput.readLine();
isErrorOut = false;
if (isPrintToConsole) {
System.out.println(line + newLineCharacter);
}
}
isErrorReady = stdError.ready();
if (isErrorReady) {
line = stdError.readLine();
isErrorError = false;
if (isPrintToConsole) {
System.out.println("ERROR: " + line + newLineCharacter);
}
}
if (!process.isAlive()) {
if (isPrintToConsole) {
System.out.println("Process DIE: " + line + newLineCharacter);
}
line = null;
isErrorError = false;
process.waitFor();
}
} while (line != null);
process.waitFor(100, TimeUnit.MILLISECONDS);
}
}https://stackoverflow.com/questions/62001222
复制相似问题