Mobile Development 3 min read

Implementing Voice Functionality in WeChat Mini Programs

This guide explains how to integrate WeChat Mini Program voice capabilities by importing the recorder and audio APIs, recording audio, uploading for speech recognition, and playing back the result, with example code snippets for each step.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Implementing Voice Functionality in WeChat Mini Programs

WeChat Mini Program voice functionality allows developers to capture spoken input, send it to WeChat's speech‑recognition service, and obtain the transcribed text.

1. Import the API

In a Mini Program JavaScript file, import the recorder and audio contexts:

<code>const recorderManager = wx.getRecorderManager();
const innerAudioContext = wx.createInnerAudioContext();</code>

recorderManager handles recording and speech recognition, while innerAudioContext is used for audio playback.

2. Recording

Start recording with the desired format (e.g., MP3):

<code>recorderManager.start({
  format: 'mp3'
});</code>

The recorder can be configured with additional parameters such as sample rate. When recording stops, the onStop callback provides a temporary file path.

3. Speech Recognition

Upload the recorded file to WeChat's voice‑to‑text API and handle the response:

<code>recorderManager.onStop((res) => {
  const { tempFilePath } = res;
  wx.uploadFile({
    url: 'https://api.weixin.qq.com/cgi-bin/media/voice/addvoicetorecofortextaccess_token=' + token + '&format=mp3&voice_id=123',
    filePath: tempFilePath,
    name: 'voice',
    success(res) {
      console.log(res.data);
    }
  });
});</code>

tempFilePath is the temporary location of the recorded audio. wx.uploadFile sends an HTTP request to the voice recognition endpoint; the result is returned in the success callback.

4. Playback

Play the recognized or any audio file using the inner audio context:

<code>innerAudioContext.autoplay = true;
innerAudioContext.src = 'http://example.com/example.mp3';</code>

Setting autoplay to true starts playback automatically, and src specifies the audio file URL.

The above steps outline the main workflow and API usage for voice features in WeChat Mini Programs; detailed comments and further implementation can be found in the official documentation.

JavaScriptWeChat Mini ProgramSpeech Recognitionaudio recordingVoice API
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.