【项目】微信录音转换为MP3格式

前言

音频转换,arm转换为MP3, 获取音频时长时长

引入maven

 <dependency>
     <groupId>com.github.dadiyang</groupId>
     <artifactId>jave</artifactId>
     <version>1.0.3</version>
 </dependency>
 

代码

引入了jar,不需要安装 ffmpeg,httpUtil.get()这是hutool里的方法

部署到线上后不行的话,就是微信后台没有给该服务器的ip过白,应该还有比较好的方法获取accessToken

public class WechatUtil {

	private static String accessToken;
    private static Long expiresTime;
    private static final String GET_ACCESSTOKEN_URL="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    public static String getAccessToken(){
        //判断accessToken是否已经过期,如果过期需要重新获取
        if(accessToken==null||expiresTime < new Date().getTime()){
            // 通过httpUtil工具类发起请求获取accessToken
            String result = HttpUtil.get(GET_ACCESSTOKEN_URL.replace("APPID", "微信公号id").replace("APPSECRET", "微信公众号密钥"));
            //把json字符串转换为json对象
            JSONObject json = JSON.parseObject(result);
            //缓存accessToken
            accessToken = json.getString("access_token");
            //设置accessToken的失效时间
            long expires_in = json.getLong("expires_in");
            System.out.println("expires_in = " + expires_in);
            //失效时间 = 当前时间 + 有效期(提前一分钟)
            expiresTime = new Date().getTime()+ (expires_in-60) * 1000;
        }
        return accessToken;
    }
	
	/**
	* 从微信服务器上下载音频
	* path:需要保存的路径:例如:D://img//
	* serverId:前端调用api上传后会返回的数据
	* openId:这个是不需要的,我只是为了确定MP3文件的唯一性,可以进行更改
	* 返回:文件地址
	**/
    public static Map<String, String> downloadFromWechat(String path, String serverId, String openId){
        String accessToken = getAccessToken();
        System.out.println("accesstoken:"+accessToken);
        String url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + accessToken + "&media_id=" + serverId;
        System.out.println("url = " + url);
        String filePath = FileUtil.saveUrlAs(url, path, "GET");
        System.err.println("filePath = " + filePath);
        String filename = String.valueOf(System.currentTimeMillis()) + ".mp3";
        String targetPath = path + openId + "-" +filename;
        File source = new File(filePath);
        File target = new File(targetPath);

		// 通过第三方jar转换为MP3,方法底层是使用了ffmpeg
        AudioUtils.amrToMp3(source, target);
//        String voiceTimes = getVoiceTimes(targetPath);
        targetPath = targetPath.substring(targetPath.lastIndexOf("/",targetPath.lastIndexOf("/")-1)+1);
        HashMap<String, String> voiceMap = new HashMap<>();

        String voiceTimes = null;
        try {
            int amrDuration = getAmrDuration(source);
            voiceTimes = String.valueOf(amrDuration) + "\"";
        } catch (IOException e) {
            e.printStackTrace();
        }
        voiceMap.put("voice", targetPath);
        voiceMap.put("voiceTime", voiceTimes);
        return voiceMap;
    }
	
	// 获取音频时长,该方法存在极小误差
	public static int getAmrDuration(File file) throws IOException {
        long duration = -1;
        int[] packedSize = { 12, 13, 15, 17, 19, 20, 26, 31, 5, 0, 0, 0, 0, 0,
                0, 0 };
        RandomAccessFile randomAccessFile = null;
        try {
            randomAccessFile = new RandomAccessFile(file, "rw");
            long length = file.length();// 文件的长度
            int pos = 6;// 设置初始位置
            int frameCount = 0;// 初始帧数
            int packedPos = -1;

            byte[] datas = new byte[1];// 初始数据值
            while (pos <= length) {
                randomAccessFile.seek(pos);
                if (randomAccessFile.read(datas, 0, 1) != 1) {
                    duration = length > 0 ? ((length - 6) / 650) : 0;
                    break;
                }
                packedPos = (datas[0] >> 3) & 0x0F;
                pos += packedSize[packedPos] + 1;
                frameCount++;
            }

            duration += frameCount * 20;// 帧数*20
        } finally {
            if (randomAccessFile != null) {
                randomAccessFile.close();
            }
        }
        return (int)((duration/1000)+1);
    }

	public static void main(String[] args) throws IOException {
        File source = new File("D:\\1656146611304.amr");
        int amrDuration = getAmrDuration(source);
        System.out.println("amrDuration = " + amrDuration);
        System.out.println("source = " + source);
        Encoder encoder = new Encoder();
        System.out.println("encoder = " + encoder);
        try {
            MultimediaInfo m = encoder.getInfo(source);
            System.out.println("m = " + m);

            long ls = m.getDuration();
            System.out.println("ls = " + ls);
            long second = ls/1000;
            System.out.println("此视频时长为:" + second + "\"");

        } catch (Exception e) {

            e.printStackTrace();

        }
    }
}
  • FileUtil

通过Java的io流写入

public class FileUtil {

    public static String saveUrlAs(String url, String filePath, String method) {
        //==
        String relfilePath = null;
        System.out.println("filePath:" + filePath);
        //System.out.println("fileName---->"+filePath);
        //创建不同的文件夹目录
        File file = new File(filePath);
        //判断文件夹是否存在
        if (!file.exists()) {
            //如果文件夹不存在,则创建新的的文件夹
            file.mkdirs();
        }
        FileOutputStream fileOut = null;
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        try {
            // 建立链接
            URL httpUrl = new URL(url);
            conn = (HttpURLConnection) httpUrl.openConnection();
            //以Post方式提交表单,默认get方式
            conn.setRequestMethod(method);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            // post方式不能使用缓存
            conn.setUseCaches(false);
            //连接指定的资源
            conn.connect();
            //获取网络输入流
            inputStream = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            //判断文件的保存路径后面是否以/结尾
            if (!filePath.endsWith("/")) {
                filePath += "/";
            }
            //写入到文件(注意文件保存路径的后面一定要加上文件的名称)
            String filename = String.valueOf(System.currentTimeMillis()) + ".amr";
            fileOut = new FileOutputStream(filePath + filename);
            relfilePath = filePath + filename;
            BufferedOutputStream bos = new BufferedOutputStream(fileOut);
            byte[] buf = new byte[4096];
            int length = bis.read(buf);
            //保存文件
            while (length != -1) {
                bos.write(buf, 0, length);
                length = bis.read(buf);
            }
            bos.close();
            bis.close();
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("抛出异常!!");

        }
        return relfilePath;

    }

}

问题

音质不容易优化,降噪不好处理…

参考文档

文档一
文档二
文档三
java将amr文件转换为MP3格式(windows&linux均可使用,亲测)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值