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

JavaScript code to achieve a simple calendar effect

This article shares the specific code for JavaScr...

MySQL GTID comprehensive summary

Table of contents 01 Introduction to GTID 02 How ...

Detailed explanation of the marquee attribute in HTML

This tag is not part of HTML3.2 and is only suppo...

Solutions for high traffic websites

First: First, confirm whether the server hardware ...

PyTorch development environment installation tutorial under Windows

Anaconda Installation Anaconda is a software pack...

Detailed explanation of CSS3 rotating cube problem

3D coordinate concept When an element rotates, it...

An article teaches you JS function inheritance

Table of contents 1. Introduction: 2. Prototype c...

25 Ways and Tips to Increase Web Page Loading Speed

Introduction <br />Not everyone has access t...

Two ways to correctly clean up mysql binlog logs

mysql correctly cleans up binlog logs Preface: Th...

How to write the Nofollow tag and how to use it

The "nofollow" tag was proposed by Goog...

Pygame code to make a snake game

Table of contents Pygame functions used Creating ...

Discussion on the problem of iframe node initialization

Today I suddenly thought of reviewing the producti...