在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
音频转码工具,主要用于将微信语音 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> 音频转码工具
|
请发表评论