Java微信语音开发

-环境、框架
一、服务器:tomcat8.0.32
二、后台框架:jfinal2.2
三、数据库:无
四、前端:wechat JS SDK
五、第三方jar:wechat4j、sauronsoftware
1、引入wechat JS SDK
这一步比较简单,按照微信给的开发文档一步一步配置就就行,可是步骤比较繁多,利用第三方依赖库wechat4j,只需几行代码便可实现JS JDK的导入。
一、首先是后台Actionhtml

public void authWeJs() {
        String url = getPara("url", null);
        long timestamp = System.currentTimeMillis() / 1000;
        String nonceStr = UUID.randomUUID().toString();
        String ticket = TokenProxy.jsApiTicket();
        String token = TokenProxy.accessToken();
        String appid = Config.instance().getAppid();
        String sortStr = "jsapi_ticket=" + ticket + "&noncestr=" + nonceStr
                + "&timestamp=" + timestamp + "&url=" + url;
        String signature = DigestUtils.sha1Hex(sortStr);
        setAttr("timestamp", timestamp);
        setAttr("signature", signature);
        setAttr("token", token);
        setAttr("appid", appid);
        setAttr("nonceStr", nonceStr);
        System.out.println(signature);
        System.out.println(sortStr);
        System.out.println(ticket);
        renderJson();
    }

二、前端JS请求Action获取接入SDK所需的appid、timestamp、nonceStr、signature前端

wx.config({
                debug: true, // 开启调试模式,调用的全部api的返回值会在客户端alert出来,若要查看传入的参数,能够在pc端打开,参数信息会经过log打出,仅在pc端时才会打印。
                appId: json.appid, // 必填,公众号的惟一标识
                timestamp:json.timestamp , // 必填,生成签名的时间戳
                nonceStr: json.nonceStr, // 必填,生成签名的随机串
                signature:json.signature,// 必填,签名,见附录1
                jsApiList: [
                            'checkJsApi',
                            'onMenuShareTimeline',
                            'onMenuShareAppMessage',
                            'onMenuShareQQ',
                            'onMenuShareWeibo',
                            'hideMenuItems',
                            'showMenuItems',
                            'hideAllNonBaseMenuItem',
                            'showAllNonBaseMenuItem',
                            'translateVoice',
                            'startRecord',
                            'stopRecord',
                            'onRecordEnd',
                            'playVoice',
                            'pauseVoice',
                            'stopVoice',
                            'uploadVoice',
                            'downloadVoice',
                            'chooseImage',
                            'previewImage',
                            'uploadImage',
                            'downloadImage',
                            'getNetworkType',
                            'openLocation',
                            'getLocation',
                            'hideOptionMenu',
                            'showOptionMenu',
                            'closeWindow',
                            'scanQRCode',
                            'chooseWXPay',
                            'openProductSpecificView',
                            'addCard',
                            'chooseCard',
                            'openCard'   
                ] // 必填,须要使用的JS接口列表,全部JS接口
            });

3、录制语言web

// 一、开始录制
wx.startRecord(); 
//二、中止录制
wx.stopRecord({
    success: function (res) {
        var localId = res.localId;
    }
});
//三、上传录制好的音频文件,注意这里是上传的微信服务器,有效期只有三天,到目前位置一直都是使用的微信SDK的API,接下来咱们须要上传到本身的服务器
wx.uploadVoice({
    localId: '', // 须要上传的音频的本地ID,由stopRecord接口得到
    isShowProgressTips: 1, // 默认为1,显示进度提示
        success: function (res) {
        var serverId = res.serverId; // 返回音频的服务器端ID
    }
});
// 四、然而JS JDK文档里面并无告知如何下载多媒体资源(微信文档的坑),不过没有关系第三方依赖库wechat4j提供了获取持久化素材的方案,几行代码就能够将多媒体资源上传到本身服务器,引入wechat4j,只需两行代码
    MediaFile mediaFile = new MediaFile();
    byte[] download = mediaFile.download(media_id);
//media_id 就是第三步骤中的serverId
// 讲byte转为file
public static void byte2File(byte[] buf, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()) {
                dir.mkdirs();
            }
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(buf);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
// 第二个坑来了,从微信服务器下载的音频文件是amr格式,然而html的audio标签并不支持amr的播放,这里咱们须要用到第二个三方依赖库sauronsoftware把amr转为MP3格式
public static void changeToMp3(String sourcePath, String targetPath) {
        File source = new File(sourcePath);
        File target = new File(targetPath);
        AudioAttributes audio = new AudioAttributes();
        Encoder encoder = new Encoder();
        audio.setCodec("libmp3lame");
        EncodingAttributes attrs = new EncodingAttributes();
        attrs.setFormat("mp3");
        attrs.setAudioAttributes(audio);
        try {
            encoder.encode(source, target, attrs);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InputFormatException e) {
            e.printStackTrace();
        } catch (EncoderException e) {
            e.printStackTrace();
        }
    }

至此,微信语言开发的流程基本结束,前端返回语音路径用audio标签播发便可
sauronsoftware.jar下载
wechat4j.jar数据库