Play and save WeChat public account recording files (convert amr files to mp3)

Play and save WeChat public account recording files (convert amr files to mp3)

Audio transcoding tool, mainly used to convert WeChat voice amr format to mp3 format so that it can be played in the audio tag of html5

1. Call the interface provided by WeChat to obtain the InputStream byte stream of the recording

public InputStream getInputStream(String mediaId) {
    InputStream is = null;
    try {
        String URL_DOWNLOAD_TEMP_MEDIA = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
        String url = URL_DOWNLOAD_TEMP_MEDIA.replace("ACCESS_TOKEN", "Write your own code to get accessToken").replace("MEDIA_ID", mediaId);
        URL urlGet = new URL(url);
        HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
        http.setRequestMethod("GET"); // Must be a get request http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        http.setDoOutput(true);
        http.setDoInput(true);
        System.setProperty("sun.net.client.defaultConnectTimeout", "30000"); // Connection timeout 30 seconds System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // Read timeout 30 seconds http.connect();
        // Get the file and convert it into byte stream is = http.getInputStream();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return is;
}

2. Save the obtained byte stream as an amr file

public String downloadMediaId(HttpServletRequest request, String mediaId) {
    String relfilePath = null;
    InputStream inputStream = getInputStream(mediaId);
    FileOutputStream fileOutputStream = null;
    try {
        //Server resource save path String savePath = request.getSession().getServletContext().getRealPath("/") + "upload/" + DateUtil.getYear() + "/wxmedia/audio/";
        savePath = savePath + "audio/"; 
        String filename = String.valueOf(System.currentTimeMillis()) + ".amr";
        relfilePath = "upload/" + DateUtil.getYear() + "/wxmedia/audio/" + filename;
        File file = new File(savePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        byte[] data = new byte[1024];
        int len ​​= 0;
        fileOutputStream = new FileOutputStream(savePath + filename);
        while ((len = inputStream.read(data)) != -1) {
            // Determine whether the result is wrong if (new String(data).indexOf("errmsg") > -1) {
                return null;
            }
            fileOutputStream.write(data, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    finally
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (fileOutputStream != null) {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return relfilePath;
}

3. Convert the saved amr file to mp3 file

public void amrToMp3(String sourcePath, String targetPath) {
    File source = new File(sourcePath);
    File target = new File(targetPath);
    AudioUtils.amrToMp3(source, target);
}

4. Required jar package dependencies

<!--amr file to audio map file-->
<dependency>
    <groupId>com.github.dadiyang</groupId>
    <artifactId>jave</artifactId>
    <version>1.0.3</version>
</dependency>

Audio transcoding tools

It supports Linux/Windows/Mac platforms because it is based on the modification of the JAVE project, and JAVE relies on ffmpeg, so it can be applied to the conversion of all file formats supported by ffmpeg. For details, please refer to the JAVE official documentation

principle

During initialization, determine the current operating environment, copy the corresponding ffmpeg executable file in the bin directory to the temporary directory, and execute the corresponding transcoding command of ffmpeg through Runtime.getRuntime().exec(cmd) according to the file type and configuration.

Problems with the JAVE Project

ffmpeg depends on the operating environment. The JAVE project encapsulates ffmpeg. Through the above principles, it enables java to call ffmpeg and supports cross-platform.

  • The project is old and no longer maintained. The latest version of the official website was released in 2009. The ffmpeg it depends on is already outdated and cannot be used in many cases.
  • EncoderException: Stream mapping
  • There is no published Maven repository, and JAVE itself is not a Maven project
  • Not supported on Mac

Features of this project

This project was created to solve the above problems.

  • This is a Maven project and has been published to the central repository.
  • The ffmpeg executable file that the project depends on has been verified to be usable (a simple verification method is provided in the unit test)
  • Solved the EncoderException: Stream mapping when converting amr to mp3
  • Support Linux/Windows/Mac platforms

Extensions

If the program cannot obtain the ffmpeg executable file by copying the resource file or the built-in ffmpeg does not support your operating system, you can specify the directory of available ffmpeg files installed in your system through environment variables or by setting System.setProperty("ffmpeg.home", "directory where the ffmpeg executable file is located") in Java.

Such as System.setProperty("ffmpeg.home", "/usr/local/bin/")

This is the end of this article about the playback and preservation of WeChat public account recording files (converting amr files to mp3). For more relevant WeChat public account recording content, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • PHP converts amr audio files into mp3 format
  • Python uses ffmpy to convert amr format audio to mp3 format example
  • asp.net audio conversion .amr to .mp3 (using ffmpeg conversion method)
  • asp.net audio conversion .amr to .mp3 (using Qiniu conversion method)

<<:  Tutorial on installing the unpacked version of mysql5.7 on CentOS 7

>>:  Tutorial on installing Tomcat server under Windows

Recommend

Nginx rewrite regular matching rewriting method example

Nginx's rewrite function supports regular mat...

WeChat Mini Program Basic Tutorial: Use of Echart

Preface Let’s take a look at the final effect fir...

Reasons for the sudden drop in MySQL performance

Sometimes you may encounter a situation where a S...

How to deal with too many Docker logs causing the disk to fill up

I have a server with multiple docker containers d...

Detailed explanation of desktop application using Vue3 and Electron

Table of contents Vue CLI builds a Vue project Vu...

An article to master MySQL index query optimization skills

Preface This article summarizes some common MySQL...

Summary of Nginx load balancing methods

To understand load balancing, you must first unde...

Two methods to implement Mysql remote connection configuration

Two methods to implement Mysql remote connection ...

Detailed explanation of common MySQL operation commands in Linux terminal

Serve: # chkconfig --list List all system service...

How to permanently change the host name in Linux

If you want to change your host name, you can fol...

XHTML Getting Started Tutorial: Using the Frame Tag

<br />The frame structure allows several web...

HTML realizes real-time monitoring function of Hikvision camera

Recently the company has arranged to do some CCFA...

Detailed explanation of dynamic Christmas tree through JavaScript

Table of contents 1. Animated Christmas Tree Made...