音频转码工具,主要用于将微信语音 amr 格式转换为 mp3 格式以便在 html5 的 audio 标签中进行播放php
1.调用微信提供的接口获取录音的InputStream字节流
public InputStream getInputStream(String mediaId) {
InputStream is = null;
try {
String URL_DOWNLOAD_TEMP_MEDIA = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
String url = URL_DOWNLOAD_TEMP_MEDIA.replace("ACCESS_TOKEN", "本身写代码获取accessToken").replace("MEDIA_ID", mediaId);
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET"); // 必须是get方式请求
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 链接超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
http.connect();
// 获取文件转化为byte流
is = http.getInputStream();
} catch (Exception e) {
e.printStackTrace();
}
return is;
}
复制代码
2.将获取到的字节流保存为amr文件
public String downloadMediaId(HttpServletRequest request, String mediaId) {
String relfilePath = null;
InputStream inputStream = getInputStream(mediaId);
FileOutputStream fileOutputStream = null;
try {
//服务器资源保存路径
String savePath = request.getSession().getServletContext().getRealPath("/") + "upload/" + DateUtil.getYear() + "/wxmedia/audio/";
savePath = savePath + "audio/";
String filename = String.valueOf(System.currentTimeMillis()) + ".amr";
relfilePath = "upload/" + DateUtil.getYear() + "/wxmedia/audio/" + filename;
File file = new File(savePath);
if (!file.exists()) {
file.mkdirs();
}
byte[] data = new byte[1024];
int len = 0;
fileOutputStream = new FileOutputStream(savePath + filename);
while ((len = inputStream.read(data)) != -1) {
// 判断结果是否有错
if (new String(data).indexOf("errmsg") > -1) {
return null;
}
fileOutputStream.write(data, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return relfilePath;
}
复制代码
3.将保存的amr文件转成mp3文件html
public void amrToMp3(String sourcePath, String targetPath) {
File source = new File(sourcePath);
File target = new File(targetPath);
AudioUtils.amrToMp3(source, target);
}
复制代码
4.所需的jar包依赖html5
<!--amr文件转音频map文件-->
<dependency>
<groupId>com.github.dadiyang</groupId>
<artifactId>jave</artifactId>
<version>1.0.3</version>
</dependency>
复制代码
支持 Linux/Windows/Mac 平台java
由于是基于 JAVE 项目的修改,而 JAVE 是依赖 ffmpeg 因此能够适用于全部 ffmpeg 所支持的文件格式的转换。具体能够查看 JAVE 官方文档git
ffmpeg 是依赖运行环境的,JAVE 项目封装了ffmpeg,它经过上述的原理使 java 能够调用ffmpeg并且支持跨平台。github
本项目为解决上述问题而生。api
若是程序没法经过拷贝资源文件的方式获取到 ffmpeg 的可执行文件或者内置的 ffmpeg 不支持你所使用的操做系统服务器
你能够经过环境变量或者在 java 中设置 System.setProperty("ffmpeg.home", "ffmpeg可执行文件所在的目录")
的方式指定你的系统中安装的可用的 ffmpeg 文件的目录微信
如 System.setProperty("ffmpeg.home", "/usr/local/bin/")
markdown