最近开发的微信项目里面需要用到微信语音的功能,结合微信开发文档的网页js接口,语音可以在网页上生成并上传到微信服务器,但是微信服务器保存的时间有限,还是保存到自己的本地服务器比较稳当,这样需要把语音文件的serverId传到后台,在后台调用微信api获取语音文件,但获取的音频文件是amr格式的,但是前端的html5的“audio”标签只支持MP3、wav、ogg三种格式,这样又需要将amr文件转为MP3文件,ffmpeg是一般的音视频文件格式转化框架。

总结一下微信语音保存展示的整体流程:

1.调用微信js,生成语音文件

2.上传语音到微信服务器

3.调用微信资源文件接口获取语音文件保存到本地服务器

4.将保存的语音文件由amr转mp3

5.用html5的audio标签播放mp3文件

前端jsp页面如下,

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<% String path = request.getContextPath(); %>
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/><meta name="viewport" content="width=640, user-scalable=no"><meta http-equiv="pragma" content="no-cache"><meta http-equiv="Cache-Control" content="no-cache"><meta http-equiv="Expires" content="0"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-status-bar-style" content="black"><meta name="format-detection" content="telephone=no"><meta name="apple-mobile-web-app-title" content=""><title>录音test</title><style type="text/css">*{ margin:0px; padding:0px; box-sizing:border-box; -webkit-tap-highlight-color:rgba(0,0,0,0);}html{ max-width:640px; margin:0 auto;}body{ font-family:"PingFangSC-Regular","sans-serif","STHeitiSC-Light","微软雅黑","Microsoft YaHei"; font-size:24px; line-height:1.5em; color:#000;-webkit-user-select:none; user-select:none;-webkit-touch-callout:none; touch-callout:none;}.start_btn , .play_btn , .send_btn{ width:250px; height:60px; line-height:60px; margin:20px auto; text-align:center; border:#eee solid 2px; cursor:pointer;}.start_btn_in , .stop_btn{ color:#f00; border:#f00 solid 2px;}</style>
</head><body><div class="start_btn">点我录音</div><div class="play_btn">点我播放</div><div class="send_btn">点我保存</div><audio id="au" src="" controls="controls"></audio><script src="<%=path%>/js/jquery-1.7.1.js" type="text/javascript"></script>
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script type="text/javascript">wx.config({debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
        appId: '${appId}', // 必填,公众号的唯一标识
        timestamp:${timestamp}, // 必填,生成签名的时间戳
        nonceStr: '${nonceStr}', // 必填,生成签名的随机串
        signature: '${signTrue}',// 必填,签名,见附录1
        jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage','startRecord','stopRecord','onVoiceRecordEnd','playVoice','stopVoice','onVoicePlayEnd','uploadVoice'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
    });wx.ready(function(){//返回音频的本地IDvar localId;//返回音频的服务器端IDvar serverId;//录音计时,小于指定秒数(minTime = 10)则设置用户未录音var startTime , endTime , minTime = 1;//***********************************////开始录音
        $('.start_btn').on('touchstart',function(e){e.preventDefault();var $this = $(this);$this.addClass('start_btn_in');startTime = new Date().getTime();//开始录音
            wx.startRecord();});//***********************************////停止录音接口
        $('.start_btn').on('touchend', function(){var $this = $(this);$this.removeClass('start_btn_in');//停止录音接口
            wx.stopRecord({success: function (res) {localId = res.localId;}});endTime = new Date().getTime();alert((endTime - startTime) / 1000);if((endTime - startTime) / 1000 < minTime){localId = '';alert('录音少于' + minTime +  '秒,录音失败,请重新录音');}});//监听录音自动停止接口
        wx.onVoiceRecordEnd({//录音时间超过一分钟没有停止的时候会执行 complete 回调
            complete: function (res) {localId = res.localId;$('.start_btn').removeClass('start_btn_in');}});//***********************************//$('.play_btn').on('click',function(){if(!localId){alert('您还未录音,请录音后再点击播放');return;}var $this = $(this);if($this.hasClass('stop_btn')){$(this).removeClass('stop_btn').text('点我播放');//停止播放接口
                wx.stopVoice({//需要停止的音频的本地ID,由 stopRecord 或 onVoiceRecordEnd 接口获得
                    localId: localId});}else{$this.addClass('stop_btn').text('点我停止');//播放语音接口
                wx.playVoice({//需要播放的音频的本地ID,由 stopRecord 或 onVoiceRecordEnd 接口获得
                    localId: localId});}});//监听语音播放完毕接口
        wx.onVoicePlayEnd({//需要下载的音频的服务器端ID,由uploadVoice接口获得
            serverId: localId,success: function (res) {$('.play_btn').removeClass('stop_btn').text('点我播放');
            }});//***********************************////上传语音接口
        $('.send_btn').on('click',function(){if(!localId){alert('您还未录音,请录音后再保存');return;}
            //上传语音接口
            wx.uploadVoice({//需要上传的音频的本地ID,由 stopRecord 或 onVoiceRecordEnd 接口获得
                localId: localId,//默认为1,显示进度提示
                isShowProgressTips: 1,success: function (res) {//返回音频的服务器端ID
                    serverId = res.serverId;$.ajax({async:true,//是否异步
                        type: "post",cache:false,dataType: "text",data:{'mediaId':serverId},url: "<%=path%>/upload/downloadVoice.do",success: function(data) {var ret = $.parseJSON(data);if (ret.statusCode == '200') {var filePath = ret.message;$("#au").attr("src",filePath);alert('已获取上传的语音文件!');} else if (ret.statusCode == '300') {alert('系统故障!');}},error: function(data){                           }});}});});});
</script>
</body>
</html>

保存语音文件如下:

public String downloadVoice(){try {if (downloadVoiceFromWx()) {ajaxDone = new AjaxDone(CommonEnum.STATUS_CODE_OK.getDescription(), "下载成功!");ajaxDone.setNavTabId(ssid);ajaxDone.setMessage(pathName);writerJson(ajaxDone);return null;} else {log.error("获取微信语音失败");}ajaxDone = new AjaxDone(CommonEnum.STATUS_CODE_ERROR.getDescription(), "下载失败!");}catch (Exception e){log.error(e +"微信语音下载失败");}writerJson(ajaxDone);return null;}public boolean downloadVoiceFromWx(){try {AccessTokenUtil accessTokenUtil = new AccessTokenUtil();String accessToken = accessTokenUtil.getAccessToken();log.info("微信accessTokenid1:" + accessToken);log.info("mediaId:" + mediaId);if (StringUtils.isEmpty(accessToken) || StringUtils.isEmpty(mediaId)) return false;String requestUrl = "";requestUrl = download_media_url.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId);log.info("获取文件的微信请求>>" + requestUrl);String vFileName = getResourceFile(requestUrl);String newVFileName = "";String extName = vFileName.substring(vFileName.lastIndexOf("."));UploadFileTypeEnum uploadFileTypeEnum = UploadFileTypeEnum.checkByExt(extName);
newVFileName = vFileName.substring(0,vFileName.lastIndexOf(".")) + ".mp3";String fileDire = getFileDirectoryPath();
amrToMp3(fileDire + vFileName,fileDire + newVFileName);

       //保存文件信息到数据库 -- 自己实现log.info("微信音频下载路径:"+ pathName);return true;}catch (Exception e){e.printStackTrace();log.error("获取音频文件失败" + mediaId);return false;}}public String getFileDirectoryPath(){String bashPath2 = null;    //访问的url中间目录=磁盘上保存的中间目录
String bashPath = Config.getConfig().get(Config.FILE_UPLOAD_PATH);    //磁盘上保存基础路径bashPath2 = Config.getConfig().get(Config.FILE_UPLOAD_URL);String savePath = bashPath + bashPath2;      //保存路径
File file = new File(savePath);if (!file.exists()) {file.mkdirs();}return savePath;}public String getResourceFile(String url){String vFileName = "";try {URL urlGet = new URL(url);HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();http.setRequestMethod("GET");http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");http.setDoOutput(true);http.setDoInput(true);http.connect();// 获取文件转化为byte流InputStream inputStream = http.getInputStream();//获取文件名String ContentDisposition = "";ContentDisposition = http.getHeaderField("Content-disposition");vFileName = ContentDisposition.substring(ContentDisposition.indexOf("filename")+10, ContentDisposition.length() -1);String vFilePath = getFileDirectoryPath() + vFileName;//写入音频新文件FileOutputStream fileOutputStream = null;int size=0;size = inputStream.available();byte[] data = new byte[size];int len = 0;fileOutputStream = new FileOutputStream(vFilePath);while ((len = inputStream.read(data)) != -1) {fileOutputStream.write(data, 0, len);}log.info("生成微信音频文件,文件为:" + vFilePath);inputStream.close();fileOutputStream.close();} catch (Exception e) {e.printStackTrace();}return vFileName;}

amr转mp3需要调用ffmpeg,下载站点:https://johnvansickle.com/ffmpeg/ 或 http://ffmpeg.org/download.html

解压文件找到ffmpeg文件,放到linux服务器目录下,然后通过java代码调用linux命令行执行转化,代码如下:

public boolean amrToMp3(String localPath, String targetFilePath) {try {log.info("**************  ffmpeg ****************");java.lang.Runtime rt = Runtime.getRuntime();String command = "/home/user/server/apache-tomcat/temp/jave-1/ffmpeg -i " + localPath + " " + targetFilePath;log.info("command = " + command);Process proc = rt.exec(command);InputStream stderr = proc.getErrorStream();InputStreamReader isr = new InputStreamReader(stderr);BufferedReader br = new BufferedReader(isr);String line = null;StringBuffer sb = new StringBuffer();while ((line = br.readLine()) != null){sb.append(line);}log.info("ffmpeg Process errorInfo: " + sb.toString());int exitVal = proc.waitFor();log.info("ffmpeg Process exitValue: " + exitVal);return true;} catch (Exception e) {log.error("ffmpeg exec cmd Exception " + e.toString());}return false;}

获取mp3文件后,audio控件直接引用linux下的该文件即可播放。

转载于:https://www.cnblogs.com/yipiaoganlu/p/9271780.html

微信语音保存到本地服务器,文件格式由amr转mp3相关推荐

  1. 获取微信用户信息后如何把微信头像保存到本地服务器

    默认微信头像是一个URL地址,保存在微信的服务器上,如果授权登录后换了头像获取的头像地址就会失效,图片显示不出来体验就会比较差.解决办法就是在登录的时候把微信头像保存到本地服务器,这样就不存在这样的情 ...

  2. asp自动解析网页中的图片地址,并将其保存到本地服务器

    程序实现功能:自动将远程页面的文件中的图片下载到本地. 程序代码 <% '将本文保存为 save2local.asp '测试:save2local.asp?url=http://ent.sina ...

  3. 如何通过讯飞语音将文本合成后的语音保存到本地

    如何通过讯飞语音将文本合成后的语音保存到本地 2014-2-21分类:Android, 解决方案, 随手实例 | 暂无评论 转自:http://www.krislq.com/2014/02/voice ...

  4. PHP ajax 远程下载PDF文件保存在本地服务器

    在一些时候我们想ajax方式来保存一些PDF文件,尤其是它放在远程服务器上,并且是保存在我们自己的服务器上存储,这个时候我们需要写一段程序来帮助我们完成这个工作,本文介绍了PHP 远程下载PDF文件保 ...

  5. 使用java生成PDF并保存到本地服务器中

    使用java生成PDF并保存到本地服务器中 1.导入maven <!-- PDF工具包 --><dependency><groupId>com.itextpdf&l ...

  6. php图片本地化,PHP_php将远程图片保存到本地服务器的实现代码,php如何将远程图片本地化,本 - phpStudy...

    php将远程图片保存到本地服务器的实现代码 php如何将远程图片本地化,本文分享了实现代码 //站点根目录 $cfg_basedir = dirname(__FILE__); //停建目录属性 $cf ...

  7. PHP 将线上的图片保存到本地服务器

    /***@describe 将远程的图片保存到本地服务器*@param $url 线上图片地址 necessary*@return*/public function getOnLineImg($url ...

  8. 通过url保存图片及微信头像保存到本地

    通过url保存图片 function dlfile($file_url, $file_name){$content = file_get_contents($file_url);file_put_co ...

  9. 微信小程序--使用本地服务器进行测试开发

    很多做微信小程序开发的程序员都是有JavaEE基础的 最近群里好多人问,小程序怎么访问本地的tomcat接口服务器,在这里记录一下 首先写一个接口,地址是"http://localhost: ...

最新文章

  1. Terracotta tc-config.xml配置说明(这个真的是转的)
  2. 干货 | 基于贝叶斯推断的分类模型 机器学习你会遇到的“坑”
  3. 最全的大数据解决方案(多图)
  4. 只允许指定IP远程桌面连接_使用IP安全策略
  5. VS2010不能断点/下断的问题
  6. 【设计模式系列】结构型模式之Proxy模式
  7. ActiveReports 6.0 - 高效开发UI
  8. 大道至简,SQL也可以实现神经网络
  9. C# 乐观锁、悲观锁、共享锁、排它锁、互斥锁
  10. step3 . day2 数据结构之线性表链表
  11. iOS核心动画之CoreAnimation
  12. 重力加速度换算_中考物理重难点汇总——公式换算大全
  13. (3.13)mysql基础深入——mysql日志分析工具之mysqlsla【待完善】
  14. Oracle 官宣:腾讯 JDK 18 国内第一!
  15. 指定版本_小米五一购机福利,购买Redmi7指定版本,送小米活塞耳机
  16. PSP3000终于可以放心的关机了!
  17. win10升级后VMware不能使用,更新升级失败
  18. 大数据学习——Hadoop本地模式搭建
  19. 装饰者模式 增加功能;动态代理减少功能 只要完成自己部分功能 (繁杂部分交给他人处理)...
  20. cv2.warpAffine 参数详解

热门文章

  1. 识字小程序—hanzi-writer-miniprogram实现临摹笔画动画播放等
  2. Linux学习(一)虚拟机安装linux资源,linux目录结构,购买阿里云服务器远程登陆linux,下载安装并使用Xshell与Xftp
  3. VScode 设置 背景图片
  4. C++实验八——类的继承(2)
  5. matlab 小游戏 找不同的颜色
  6. flink 分词程序代码(批处理和实时)
  7. Caused by: java.lang.UnsatisfiedLinkError: Library hello-jni not found“问题解决
  8. 矩阵的entries
  9. 《开天辟地》之《网上冲浪篇》将带你进入一个精彩的互联网世界
  10. PrimeNG p-Table 自定义shift多选功能