微信公众号录音文件保存到自己开发的服务器(amr文件转mp3)

音频转码工具,主要用于将微信语音 amr 格式转换为 mp3 格式以便在 html5 的 audio 标签中进行播放

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文件

public void amrToMp3(String sourcePath, String targetPath) {
    File source = new File(sourcePath);
    File target = new File(targetPath);
    AudioUtils.amrToMp3(source, target);
}

4.所需的jar包依赖

<!--amr文件转音频map文件-->
<dependency>
    <groupId>com.github.dadiyang</groupId>
    <artifactId>jave</artifactId>
    <version>1.0.3</version>
</dependency>

音频转码工具

支持 Linux/Windows/Mac 平台

因为是基于 JAVE 项目的修改,而 JAVE 是依赖 ffmpeg 所以可以适用于所有 ffmpeg 所支持的文件格式的转换。具体可以查看 JAVE 官方文档

原理

  1. 初始化时判断当前运行环境,将bin目录中对应的 ffmpeg 可执行文件拷贝到临时目录中
  2. 根据文件类型及配置通过 Runtime.getRuntime().exec(cmd) 执行 ffmpeg 对应的转码命令

JAVE 项目的问题

ffmpeg 是依赖运行环境的,JAVE 项目封装了ffmpeg,它通过上述的原理使 java 可以调用ffmpeg而且支持跨平台。

  1. 项目老旧没再维护。官网最近版本是2009年发布的,其依赖的ffmpeg早已过时,很多情况下用不了。
  2. 转码一直报异常 EncoderException: Stream mapping
  3. 没有发布maven仓库,而且 JAVE 本身也不是一个maven项目
  4. 不支持mac

本项目特点

本项目为解决上述问题而生。

  • 这是一个maven项目,而且已发布到中央仓库
  • 项目依赖的 ffmpeg 可执行文件经过验证可以使用(单元测试中提供了一个简单的检验方法)
  • 解决了amr转mp3出现的 EncoderException: Stream mapping
  • 支持 Linux/Windows/Mac 平台

扩展

如果程序无法通过拷贝资源文件的方式获取到 ffmpeg 的可执行文件或者内置的 ffmpeg 不支持你所使用的操作系统

你可以通过环境变量或者在 java 中设置 System.setProperty("ffmpeg.home", "ffmpeg可执行文件所在的目录") 的方式指定你的系统中安装的可用的 ffmpeg 文件的目录

如 System.setProperty("ffmpeg.home", "/usr/local/bin/")

猜你喜欢

转载自blog.csdn.net/qq_24101357/article/details/86592298