小程序项目最初使用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();
}

输出结果

1
2
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。

1
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();
}

输出结果

1
2
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

1
2
3
4
5
6
7
8
9
10
11
12
* <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();
}

输出结果

1
2
3
4
5
6
7
8
9
10
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才发现掉坑了。
正确的写法

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

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

1
2
3
Process p = new ProcessBuilder().command("ping", "-n", "1", "127.0.0.1")
.redirectError(new File("stderr.txt"))
.start();

工作目录

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

一些代码细节

ProcessBuilder.Redirect

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

1
2
3
4
5
6
7
public enum Type {
PIPE,
INHERIT,
READ,
WRITE,
APPEND
};

其中

  • PIPE: 表示子流程IO将通过管道连接到当前的Java进程。 这是子进程标准IO的默认处理。
  • INHERIT: 表示子进程IO源或目标将与当前进程的相同。 这是大多数操作系统命令解释器(shell)的正常行为。

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

  • append
  • appendTo
  • file
  • from
  • to

Runtime.exec()的实现

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

1
2
3
4
5
6
7
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()方法

1
2
3
FileInputStream  f0 = null;
FileOutputStream f1 = null;
FileOutputStream f2 = null;

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

总结

  • Process类是java对进程的抽象。ProcessImpl是具体的实现。
  • Runtime.getRuntime().exec()和ProcessBuilder.start()都能启动子进程。Runtime.getRuntime().exec()底层也是ProcessBuilder构造的
  • Runtime.getRuntime().exec()可以直接消费一整串带空格的命令。但是ProcessBuilder.command()必须要以字符串数组或者list形式传入参数
  • 默认子进程的执行和父进程是异步的。可以通过Process.waitFor()实现阻塞等待。
  • 默认情况下,子进程和父进程共享stdin、stdout、stderr。ProcessBuilder支持对流的重定向(since java7)
  • 流的重定向,是通过ProcessBuilder.Redirect类实现。

ProcessBuilder waitFor 调用外部应用的更多相关文章

  1. JDK1.5新特性,基础类库篇,调用外部命令类(ProcessBuilder)用法

    一. 背景 ProcessBuilder类是用来创建操作系统进程的.与Runtime.exec相比,它提供了更加方便的方法以创建子进程. 每个ProcessBuilder实例管理着一个进程属性的集合. ...

  2. System.Diagnostics.Process 启动进程资源或调用外部的命令的使用

    经常看到一些程序在保存为一个txt,或者excel的文件的时候,保存完毕立即打开, 启动程序或打开文件的代码 System.Diagnostics.Process.Start(System.IO.Pa ...

  3. python调用外部子进程,通过管道实现异步标准输入和输出的交互

    我们通常会遇到这样的需求:通过C++或其他较底层的语言实现了一个复杂的功能模块,需要搭建一个基于Web的Demo,方法查询数据.由于Python语言的强大和简洁,其用来搭建Demo非常合适,Flask ...

  4. 关于js调用外部部署的web api

    没想到多年之后我还得继续写这些东西.... 瀑布汗~ 最近不得不开始研究用web api MVC的项目中,在js文件里,实现点击一个按钮调用外部发布好的api,再从api把值回传给js页面,跳转. 经 ...

  5. windows下调用外部exe程序 SHELLEXECUTEINFO

    本文主要介绍两种在windows下调用外部exe程序的方法: 1.使用SHELLEXECUTEINFO 和 ShellExecuteEx SHELLEXECUTEINFO 结构体的定义如下: type ...

  6. 在Salesforce中调用外部系统所提供的的Web Service

    这里需要提供外部service所对应的WSDL文件(Salesforce只支持从本地上传),并且提供的WSDL文件有如下两点要求: 1):wsdl 文件只能有一个binding,Salesforce是 ...

  7. QTP学习一添加默认的注释及调用外部vbs文件

    一.添加默认注释 1.新建一个TXT文档,将要添加的注释写在文档中 2.再将文档名改为:ActionTemplate.mst 3.将文件放到QTP安装目录(默认为:C:\Program Files\H ...

  8. Android 使用AIDL调用外部服务

    好处:多个应用程序之间建立共同的服务机制,通过AIDL在不同应用程序之间达到数据的共享和数据相互操作, 本文包括: 1 .创建AIDL 服务端.2 .创建AIDL 客户端. 3.客户端调用服务端提供的 ...

  9. Perl调用外部命令的方式和区别

    主要的方式简述如下:1. system("command");使用该命令将开启一个子进程执行引号中的命令,父进程将等待子进程结束并继续执行下面的代码. 2. exec(" ...

随机推荐

  1. C语言实现贪吃蛇

    日期:2018.9.11 用时:150min 项目:贪吃蛇(C语言--数组   结构体实现) 开发工具:vs2013 关键知识:数组,结构体,图形库,键位操作 源代码: #include<std ...

  2. kubernetes实战篇之helm示例yaml文件文件详细介绍

    系列目录 前面完整示例里,我们主要讲解helm打包,部署,升级,回退等功能,关于这里面的文件只是简单介绍,这一节我们详细介绍一下这里面的文件,以方便我们参照创建自己的helm chart. Helm ...

  3. spring-boot-plus后台快速开发框架1.0.0.RELEASE发布了

    spring-boot-plus spring-boot-plus是一套集成spring boot常用开发组件的后台快速开发框架 官网地址:springboot.plus GITHUB:https:/ ...

  4. HDU 1828:Picture(扫描线+线段树 矩形周长并)

    题目链接 题意 给出n个矩形,求周长并. 思路 学了区间并,比较容易想到周长并. 我是对x方向和y方向分别做两次扫描线.应该记录一个pre变量,记录上一次扫描的时候的长度,对于每次遇到扫描线统计答案的 ...

  5. MyBatis 基础搭建及架构概述

    目录 MyBatis 是什么? MyBatis 项目构建 MyBatis 整体架构 接口层 数据处理层 基础支持层 MyBatis 是什么? MyBatis是第一个支持自定义SQL.存储过程和高级映射 ...

  6. Jmeter接口测试实例-牛刀小试

    本次测试的是基于HTTP协议的接口,主要是通过Jmeter来完成接口测试,借此熟悉Jmeter的基本操作. 本次实战,我是从网上找的接口测试项目,该项目提供了详细的接口文档,我们可以通过学习接口文档来 ...

  7. Ray-基础部分目录

    基础部分: 引言 Actor编写-ESGrain与ESRepGrain 消息发布器与消息存储器 Event编写 Handler之CoreHandler编写 Handler之ToReadHandler编 ...

  8. Linux系统-CENTOS7使用笔记

    复制文件夹下的所有文件到另一个文件夹下 cp ~/dirname/* ~/otherdirname 解压rar文件 PS:在liunx下原本是不支持rar文件的,需要安装liunx下的winrar版本 ...

  9. 浅入深出Vue:代码整洁之封装

    深入浅出vue系列文章已经更新过半了,在入门篇中我们实践了一个小小的项目. <代码整洁之道>一书中提到过一句话: 神在细节中 这句话来自20世纪中期注明现代建筑大师 路德维希·密斯·范·德 ...

  10. kali linux 常用文件与指令路径

    重启网络 : /etc/init.d/networking restart 语言设置文件 : /etc/default/locale apt 安装deb保存目录 : /var/cache/apt/ar ...