加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

ProcessBuilder waitFor 调用外部应用

发布时间:2020-12-14 19:11:56 所属栏目:资源 来源:网络整理
导读:小程序项目最初使用ffmpeg转换微信录音文件为wav格式,再交给阿里云asr识别成文字。视频音频转换最常用是ffmpeg。 1 ffmpeg -i a.mp3 b.wav 相关文章: 小程序实现语音识别转文字,坑路历程 问题变成怎样使用java调用系统的ffmpeg工具。在java中,封装了进程

小程序项目最初使用ffmpeg转换微信录音文件为wav格式,再交给阿里云asr识别成文字。视频音频转换最常用是ffmpeg。

1
ffmpeg -i a.mp3 b.wav

相关文章:

  • 小程序实现语音识别转文字,坑路历程

问题变成怎样使用java调用系统的ffmpeg工具。在java中,封装了进程Process类,可以使用Runtime.getRuntime().exec()或者ProcessBuilder新建进程。

从Runtime.getRuntime().exec()说起

最简单启动进程的方式,是直接把完整的命令作为exec()的参数。

1
2
3
4
5
6
7
try {
log.info("ping 10 times");
Runtime.getRuntime().exec("ping -n 10 127.0.0.1");
log.info("done");
} catch (IOException e) {
e.printStackTrace();
}

输出结果

1
2
17:12:37.262 [main] INFO com.godzilla.Test - ping 10 times
17:12:37.272 [main] INFO com.godzilla.Test - done

我期望的是执行命令结束后再打印done,但是明显不是。

waitFor阻塞等待子进程返回

Process类提供了waitFor方法。可以阻塞调用者线程,并且返回码。0表示子进程执行正常。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* Causes the current thread to wait,if necessary,until the
* process represented by this {@code Process} object has
* terminated. This method returns immediately if the subprocess
* has already terminated. If the subprocess has not yet
* terminated,the calling thread will be blocked until the
* subprocess exits.
*
* @return the exit value of the subprocess represented by this
* {@code Process} object. By convention,the value
* {@code 0} indicates normal termination.
* @throws InterruptedException if the current thread is
* {@linkplain Thread#interrupt() interrupted} by another
* thread while it is waiting,then the wait is ended and
* an {@link InterruptedException} is thrown.
*/
public abstract int waitFor() throws InterruptedException;
1
2
3
4
5
6
7
8
9
10
11
12
try {
log.info("ping 10 times");
Process p = Runtime.getRuntime().exec("ping -n 10 127.0.0.1");
int code = p.waitFor();
if(code == 0){
log.info("done");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}

17:15:28.557 [main] INFO com.godzilla.Test - ping 10 times
17:15:37.615 [main] INFO com.godzilla.Test - done

似乎满足需要了。但是,如果子进程发生问题一直不返回,那么java主进程就会一直block,这是非常危险的事情。
对此,java8提供了一个新接口,支持等待超时。注意接口的返回值是boolean,不是int。当子进程在规定时间内退出,则返回true。

public boolean waitFor(long timeout,TimeUnit unit)

测试代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
try {
log.info("ping 10 times");
Process p = Runtime.getRuntime().exec("ping -n 10 127.0.0.1");
boolean exit = p.waitFor(1,TimeUnit.SECONDS);
if (exit) {
log.info("done");
} else {
log.info("timeout");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}

17:43:47.340 [main] INFO com.godzilla.Test - ping 10 times
17:43:48.352 [main] INFO com.godzilla.Test - timeout

获取输入、输出和错误流

要获取子进程的执行输出,可以使用Process类的getInputStream()。类似的有getOutputStream()getErrorStream()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
try {
log.info("ping");
Process p = Runtime.getRuntime().exec("ping -n 1 127.0.0.1");
p.waitFor();
BufferedReader bw = new BufferedReader(new InputStreamReader(p.getInputStream(),"GBK"));
String line = null;
while ((line = bw.readLine()) != null) {
System.out.println(line);
}
bw.close();
log.info("done")
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}

注意,GBK是Windows平台的字符编码。
输出结果

1
2
3
4
5
6
7
8
9
10
18:28:21.396 [main] INFO com.godzilla.Test - ping

正在 Ping 127.0.0.1 具有 32 字节的数据:
来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=128

127.0.0.1 的 Ping 统计信息:
数据包: 已发送 = 1,已接收 = 1,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
最短 = 0ms,最长 = 0ms,平均 = 0ms
18:28:21.444 [main] INFO com.godzilla.Test - done

这里牵涉到一个技术细节,参考Process类的javadoc

* <p>By default,the created subprocess does not have its own terminal
* or console. All its standard I/O (i.e. stdin,stdout,stderr)
* operations will be redirected to the parent process,where they can
* be accessed via the streams obtained using the methods
* {@link #getOutputStream()},
* {@link #getInputStream()},and
* {@link #getErrorStream()}.
* The parent process uses these streams to feed input to and get output
* from the subprocess. Because some native platforms only provide
* limited buffer size for standard input and output streams,failure
* to promptly write the input stream or read the output stream of
* the subprocess may cause the subprocess to block,or even deadlock.

翻译过来是,子进程默认没有自己的stdin、stdout、stderr,涉及这些流的操作,到会重定向到父进程。由于平台限制,可能导致缓冲区消耗完了,导致阻塞甚至死锁!

网上有的说法是,开启2个线程,分别读取子进程的stdout、stderr。
不过,既然说是By default,就是有非默认的方式,其实就是使用ProcessBuilder类,重定向流。此功能从java7开始支持。

ProcessBuilder和redirect

1
2
3
4
5
6
7
8
try {
log.info("ping");
Process p = new ProcessBuilder().command("ping -n 1 127.0.0.1").start();
p.waitFor();
log.info("done")
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}

输出结果

19:01:53.027 [main] INFO com.godzilla.Test - ping
java.io.IOException: Cannot run program "ping -n 1 127.0.0.1": CreateProcess error=2,系统找不到指定的文件。
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
at com.godzilla.Test.main(Test.java:13)
Caused by: java.io.IOException: CreateProcess error=2,系统找不到指定的文件。
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(ProcessImpl.java:386)
at java.lang.ProcessImpl.start(ProcessImpl.java:137)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
... 1 more

此处有坑:ProcessBuilder的command列表要用字符串数组或者list形式传入! ps. 在小程序项目上,一开始把ffmpeg -i a.mp3 b.wav传入ProcessBuilder,却看不到生成的wav文件,查了日志CreateProcess error=2,系统找不到指定的文件。还以为是ffmpeg路径问题。后来查了api才发现掉坑了。
正确的写法

Process p = new ProcessBuilder().command("ping","-n","1","127.0.0.1").start();

刚才说的重定向问题,可以这样写

1
2
3
"127.0.0.1")
.redirectError(new File("stderr.txt"))
.start();

工作目录

默认子进程的工作目录继承于父进程。可以通过ProcessBuilder.directory()修改。

一些代码细节

ProcessBuilder.Redirect

java7增加了ProcessBuilder.Redirect抽象,实现子进程的流重定向。Redirect类有个Type枚举

public enum Type {
PIPE,
INHERIT,
READ,
WRITE,
APPEND
};

其中

对于不同类型的Redirect,覆盖下面的方法

Runtime.exec()的实现

Runtime类的exec()底层也是用ProcessBuilder实现

public Process exec(String[] cmdarray,String[] envp,File dir)
throws IOException {
return new ProcessBuilder(cmdarray)
.environment(envp)
.directory(dir)
.start();
}

ProcessImpl

Process的底层实现类是ProcessImpl。
上面讲到流和Redirect,具体在ProcessImpl.start()方法

FileInputStream  f0 = null;
FileOutputStream f1 = null;
FileOutputStream f2 = null;

然后是一堆繁琐的if…else判断是Redirect.INHERIT、Redirect.PIPE,是输入还是输出流。

总结

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

相关内容
推荐文章
站长推荐
热点阅读