Java 微信获取临时素材(录音)并上传到服务器

1.音频转码工具

AudioUtils.amrToMp3

2.获取临时素材

微信获取临时素材对接代码

3.代码

	/**
     * 微信获取临时素材(录音)并上传到服务器
     *
     * @param mediaId
     * @author hcx
     * @since 2024-01-03
     * @return 上传之后的url
     */
    public String recording(String mediaId) throws IOException {
        // 获取临时素材(录音)文件流
        InputStream inputStream = weChatService.getTemporaryMaterial(mediaId);
        OutputStream outputStream = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            // 服务器路径
            String serverUrl = "服务器路径1/路径2/...";
            // 相对文件路径
            String relativeUrl = "/mp3" + "/" + sdf.format(new Date());
            // 文件名(不包括文件后缀)
            String fileName = "/" + System.currentTimeMillis() + UUID.randomUUID().toString().replace("-", "");

            // 判断是否存在当前目录,不存在则创建
            File filePath = new File(serverUrl + relativeUrl);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }

            // 1.将文件流写到服务器,变成amr文件
            File amrFile = new File(serverUrl + relativeUrl + fileName + ".amr");   // amr文件
            outputStream = new FileOutputStream(amrFile);
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            // 完毕,关闭所有链接
            outputStream.close();
            inputStream.close();

            // 2.将amr文件转为mp3,再写到服务器
            File mp3File = new File(serverUrl + relativeUrl + fileName + ".mp3"); // mp3文件
            AudioUtils.amrToMp3(amrFile, mp3File);

            // 3.删除服务器的amr文件
            Path path = Paths.get(serverUrl + relativeUrl + fileName + ".amr");
            Files.delete(path);

            String url = relativeUrl + fileName + ".mp3";
            return url;

        } catch (Exception e){
            e.printStackTrace();
            logger.error("微信获取临时素材(录音)并上传到服务器失败:" + e);
        }
        return null;
    }
  • 12
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您解答关于Java调用企业微信临时素材获取media_id的问题。 首先,您需要准备好以下信息: 1. 企业微信的CorpID和Secret。 2. 上临时素材文件,可以是图片、音频、视频等。 3. 文件的类型,例如:image、voice、video等。 然后,您可以按照以下步骤进行操作: 1. 构造请求URL:https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE 其中,ACCESS_TOKEN是企业微信的接口调用凭证,可以通过企业微信的API获取;TYPE是上临时素材的类型。 2. 发送HTTP POST请求,上临时素材文件。 3. 解析返回结果。如果上成功,返回的JSON数据中会包含media_id字段,该字段即为上临时素材的media_id。 以下是一个Java调用企业微信临时素材获取media_id的示例代码: ``` public String uploadTempMedia(String filePath, String type, String accessToken) { String result = null; File file = new File(filePath); String url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=" + accessToken + "&type=" + type; try { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Connection", "Keep-Alive"); httpPost.setHeader("Cache-Control", "no-cache"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addBinaryBody("media", file, ContentType.DEFAULT_BINARY, file.getName()); HttpEntity entity = builder.build(); httpPost.setEntity(entity); CloseableHttpResponse response = httpClient.execute(httpPost); try { HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { String responseStr = EntityUtils.toString(responseEntity, "UTF-8"); JSONObject jsonObject = JSONObject.fromObject(responseStr); result = jsonObject.getString("media_id"); } } finally { response.close(); } } catch (Exception e) { e.printStackTrace(); } return result; } ``` 您只需要将filePath、type、accessToken三个参数替换成您自己的值,即可使用该方法上临时素材获取media_id。 希望这个回答能够帮到您!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值