SpringBoot开发微信临时素材下载及录音格式转换MP3

简介:

前端调用拍照或者录音等接口完成后会获取到微信返回的serverId(mediaId),将mediaId传给后端,后端就可以拿着该id调用微信的临时素材接口下载所需的素材。

依赖:

        <!-- 文件格式转换依赖 -->
        <!-- https://mvnrepository.com/artifact/ws.schild/jave-core -->
        <dependency>
            <groupId>ws.schild</groupId>
            <artifactId>jave-core</artifactId>
            <version>2.4.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-mock -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-mock</artifactId>
            <version>2.0.8</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/ws.schild/jave-native-win64     Windows版本-->
        <dependency>
            <groupId>ws.schild</groupId>
            <artifactId>jave-native-win64</artifactId>
            <version>2.4.4</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/ws.schild/jave-native-linux64   Linux版本-->
        <dependency>
            <groupId>ws.schild</groupId>
            <artifactId>jave-native-linux64</artifactId>
            <version>2.4.4</version>
        </dependency>

工具类(下载素材及获取Token类):

package com.ruoyi.project.mobile.utils;

import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import ws.schild.jave.AudioAttributes;
import ws.schild.jave.Encoder;
import ws.schild.jave.EncodingAttributes;
import ws.schild.jave.MultimediaObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class DloadImgUtil {

    /**

     * 根据内容类型判断文件扩展名

     *

     * @param contentType 内容类型

     * @return

     */

    public static String getFileexpandedName(String contentType) {

        String fileEndWitsh = "";

        if ("image/jpeg".equals(contentType))

            fileEndWitsh = ".jpg";

        else if ("audio/mpeg".equals(contentType))

            fileEndWitsh = ".mp3";

        else if ("image/png".equals(contentType))

            fileEndWitsh = ".png";

        else if ("image/jpg".equals(contentType))

            fileEndWitsh = ".jpg";

        else if ("audio/amr".equals(contentType))

            fileEndWitsh = ".amr";

        else if ("video/mp4".equals(contentType))

            fileEndWitsh = ".mp4";

        else if ("video/mpeg4".equals(contentType))

            fileEndWitsh = ".mp4";

        return fileEndWitsh;

    }

    /**
     * 获取媒体文件
     * @param accessToken 接口访问凭证
     * @param savePath 文件在服务器上的存储路径
     * */
    public static String downloadMedia(String accessToken, String mediaId, String savePath) {
        String filePath = null;
        String fileExt = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID&debug=1";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId);

        try {
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setRequestMethod("GET");
            if (!savePath.endsWith("/")) {
                savePath += "/";
            }
            // 根据内容类型获取扩展名
            fileExt = getFileexpandedName(conn.getHeaderField("Content-Type"));
            // 将mediaId作为文件名
            filePath = savePath + mediaId + fileExt;
            BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
            FileOutputStream fos = new FileOutputStream(new File(filePath));
            byte[] buf = new byte[8096];
            int size = 0;
            while ((size = bis.read(buf)) != -1)
                fos.write(buf, 0, size);
            fos.close();
            bis.close();
            conn.disconnect();
            String info = String.format("下载媒体文件成功,filePath=" + filePath);
        } catch (Exception e) {
            filePath = null;
            String error = String.format("下载媒体文件失败:%s", e);
        }
        String newPath = null;
        if(filePath.contains(".amr")) {
            newPath = savePath + mediaId + ".mp3";
            formatConversion(filePath,newPath);
            return "/profile" + "/mobile/" + mediaId + ".mp3";
        }
        return "/profile" + "/mobile/" + mediaId + fileExt;
    }

    /**
     * 文件格式转换
     *
     * @return
     */
    public static MultipartFile formatConversion(String resourcePath,String targetPath) {
        MockMultipartFile mockMultipartFile = null;
        try {
            File source = new File(resourcePath);
            File target = new File(targetPath);
            //Audio Attributes
            AudioAttributes audio = new AudioAttributes();
            audio.setCodec("libmp3lame");
            audio.setBitRate(128000);
            audio.setChannels(2);
            audio.setSamplingRate(44100);
            //Encoding attributes
            EncodingAttributes attrs = new EncodingAttributes();
            attrs.setFormat("mp3");
            attrs.setAudioAttributes(audio);
            //Encode
            Encoder encoder = new Encoder();
            encoder.encode(new MultimediaObject(source), target, attrs);
            //转MultipartFile
            FileInputStream fileInputStream = new FileInputStream(target);
            mockMultipartFile = new MockMultipartFile(target.getName(), fileInputStream);
            System.out.println("转换完成");
        } catch (Exception ex) {
            System.out.println("转换失败");
            ex.printStackTrace();
        }
        return mockMultipartFile;
    }



}
package com.ruoyi.project.mobile.utils;


import static java.lang.Thread.sleep;
import net.sf.json.JSONObject;

public class GetToken {


    public static String getAccseeToken() throws Exception {
        String access_tocken = null;
        //访问地址
        String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
        //appid
        String APPID = "xxxxxxxxx";
        //appsecret
        String APPSECRET = "xxxxxxxxxxx";

        String request_url = TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
        HttpsUtil httpsUtil = new HttpsUtil();
        System.out.println(request_url);
        int i = 0;
            JSONObject jsonObject = httpsUtil.HttpsUtil(request_url,"GET",null);
            if(null != jsonObject){
                access_tocken = jsonObject.getString("access_token");
                String expires_in = jsonObject.getString("expires_in");
                //获取到的access_tocken值可以写入到文本文件中供其他业务逻辑调用,实例中只打印了没有保存到文件
                System.out.println("获取成功"+"access_tocken="+access_tocken+"||expires_in="+expires_in);
                i=Integer.parseInt(expires_in);
            }
        return access_tocken;

    }
}

使用:

    @GetMapping("/downloadWxFiles")
    @ResponseBody
    public String downloadWxFiles(String mediaId) {
        /**
         * 下载多媒体文件
         */
        String token = null;
        try {
            token = GetToken.getAccseeToken();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String savePath = DloadImgUtil.downloadMedia(token, mediaId, "/home/hb/uploadPath/mobile/");
        System.out.println("录音路径:" + savePath);
        if(!StringUtils.contains(savePath,".")) {
            return "error";
        }
        return savePath;
    }

Spring Boot开发微信素材永久上传接口需要进行以下步骤: 1. 导入必要的依赖:首先在pom.xml文件中添加相关的依赖,如Spring Web、Spring Boot DevTools以及第三方库如Apache HttpComponents等。 2. 创建Access Token获取接口:微信接口需要Access Token进行身份验证。可以创建一个Controller类,定义一个调用微信API获取Access Token的方法,并使用Scheduled定时任务来定期刷新Access Token。在该方法中,可以使用HttpComponents库来发送请求并解析返回的JSON数据,最后将获取到的Access Token存储在一个全局变量中。 3. 创建素材上传接口:同样,创建一个Controller类,并定义一个用于处理上传素材的方法。在该方法中,需要先获取到之前获取的Access Token,然后使用HttpComponents库发送POST请求,将素材文件内容作为请求的Body发送给微信API。 4. 处理上传结果:根据微信API返回的结果,可以采取不同的处理方式。如果上传成功,可以将返回的MediaId等相关信息保存到数据库中。如果上传失败,可以返回相应的错误信息。 5. 配置文件设置:在application.properties或application.yml(根据实际使用的配置文件类型而定)中设置微信公众号的相关配置信息,如AppID、AppSecret等。在Controller类中可以通过@Value注解来读取并使用这些配置信息。 6. 异常处理:当出现异常情况时,可以使用Spring Boot的全局异常处理机制来统一处理异常,返回相应的错误信息。 通过以上步骤,我们可以在Spring Boot开发一个用于微信素材永久上传的接口。接口可以通过访问URL来调用,将素材文件上传到微信服务器,并将上传结果返回给调用方。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值