为了账号安全,请及时绑定邮箱和手机立即绑定

一篇文章教会你用Java微信语音开发

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

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
                + "×tamp=" + 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();
    }

2、前端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接口
            });

三、录制语言

// 1、开始录制
wx.startRecord(); 
//2、停止录制
wx.stopRecord({
    success: function (res) {
        var localId = res.localId;
    }
});
//3、上传录制好的音频文件,注意这里是上传的微信服务器,有效期只有三天,到目前位置一直都是使用的微信SDK的API,接下来我们需要上传到自己的服务器
wx.uploadVoice({
    localId: '', // 需要上传的音频的本地ID,由stopRecord接口获得
    isShowProgressTips: 1, // 默认为1,显示进度提示
        success: function (res) {
        var serverId = res.serverId; // 返回音频的服务器端ID
    }
});
// 4、然而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标签播发即可

点击查看更多内容
13人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
JAVA开发工程师
手记
粉丝
8549
获赞与收藏
6550

关注作者,订阅最新文章

阅读免费教程

感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消