WeChat mini program
This topic describes how to use the WeChat mini program software development kit (SDK) for Alibaba Cloud Voice Service. It covers how to install the SDK and provides a code example.
Prerequisites
Before you use the SDK, review the API reference. For more information, see API reference.
Download and install
Download and install the SDK.
You can download the SDK code from Github or download the alibabacloud-nls-wx-sdk-master.zip file directly.
Import the SDK.
Copy the downloaded code to a folder in your project. Then, import the SDK using `require` and specifying the folder path.
Get a token
getToken
This method obtains a token and caches it using the AKID (AccessKey ID) and AKKEY (AccessKey Secret) as keys. If the cached token expires, the method automatically refreshes the token. For more information about the caching mechanism, see the Data Caching topic in the WeChat Mini Program documentation.
Parameters: None.
Return value: A string that represents the token.
getTokenInner
This method directly retrieves a token without using the caching mechanism. This method is suitable for custom caching.
Parameters: None.
Return value: A string that represents the token.
The server denies frequent calls to this API.
Real-time speech recognition
Class: SpeechTranscription
The SpeechTranscription class is used for real-time speech recognition.
Constructor parameters:
Parameter | Type | Description |
config | Object | The connection configuration object. |
config object description:
Parameter | Type | Description |
url | String | The service URL. |
token | String | The access token. For more information, see Get a token. |
appkey | String | The AppKey of the project. To get an AppKey, go to the console. |
defaultStartParams()
This method returns a set of default recommended parameters. In the default parameters, the format is PCM, the sample rate is 16000 Hz, and intermediate results, punctuation prediction, and Inverse Text Normalization (ITN) are enabled. After you obtain the default object, you can add or modify parameters as needed based on the parameter list in the API reference.
Parameters: None.
Return value:
An object with the following fields:
{ "format": "pcm", "sample_rate": 16000, "enable_intermediate_result": true, "enable_punctuation_predition": true, "enable_inverse_text_normalization": true }
on(which, handler)
This method sets an event callback.
Parameters:
Parameter | Type | Description |
which | String | The event name. |
handler | Function | The callback function. |
The supported callback events are as follows:
Event name | Description | Number of callback function parameters | Callback function parameter description |
started | Real-time speech recognition starts. | 1 | String type. The start message. |
changed | An intermediate result of real-time speech recognition. | 1 | String type. The intermediate result message. |
completed | Real-time speech recognition is complete. | 1 | String type. The completion message. |
closed | The connection is closed. | 0 | None. |
failed | An error occurred. | 1 | String type. The error message. |
begin | Indicates the start of a sentence. | 1 | String type. Related information. |
end | Indicates the end of a sentence. | 1 | String type. Related information. |
Return value: None.
async start(param)
This method starts a speech recognition task based on the `param` parameter. The `param` can be the object returned by the `defaultStartParams` method. For details about all parameters, see the API reference.
Parameters:
Parameter | Type | Description |
param | Object | The real-time speech recognition parameters. |
Return value: A Promise object. The `resolve` function is triggered after the `started` event occurs and passes the `started` message. The `reject` function is triggered if an error occurs and passes the exception information.
async close(param)
This method stops the speech recognition task.
Parameters:
Parameter | Type | Description |
param | Object | Parameters for ending the real-time speech recognition task. |
Return value:
A Promise object. The `resolve` function is triggered after the `completed` event occurs and passes the `completed` message. The `reject` function is triggered if an error occurs and passes the exception information.
shutdown()
This method forcibly disconnects the connection.
Parameters: None.
Return value: None.
sendAudio(data)
This method sends audio data. The audio format must be the same as the format specified in the parameters.
Parameters:
Parameter | Type | Description |
data | ArrayBuffer | Binary audio data. |
Return value: None.
Code example
The following code example is for reference only. The code uses the built-in recording feature of WeChat mini programs. In a real-world application, you must consider the limitations of WeChat mini programs, your frontend page design, and your specific business features.
// pages/st/st.js
const app = getApp()
const AKID = "Your AKID"
const AKKEY = "Your AKKEY"
const getToken = require("../../utils/token").getToken
const SpeechTranscription = require("../../utils/st")
const sleep = require("../../utils/util").sleep
Page({
/**
* Initial data of the page.
*/
data: {
stStart : false,
stResult : "Recognition not started"
},
/**
* Lifecycle function--Called when the page loads.
*/
onLoad: async function (options) {
wx.getRecorderManager().onFrameRecorded((res)=>{
if (res.isLastFrame) {
console.log("record done")
}
if (this.data.st && this.data.stStart) {
console.log("send " + res.frameBuffer.byteLength)
this.data.st.sendAudio(res.frameBuffer)
}
})
wx.getRecorderManager().onStart(()=>{
console.log("start recording...")
})
wx.getRecorderManager().onStop((res) => {
console.log("stop recording...")
if (res.tempFilePath) {
wx.removeSavedFile({
filePath:res.tempFilePath
})
}
})
wx.getRecorderManager().onError((res) => {
console.log("recording failed:" + res)
})
try {
this.data.token = await getToken(AKID, AKKEY)
} catch (e) {
console.log("error on get token:", JSON.stringify(e))
return
}
let st = new SpeechTranscription({
url : app.globalData.URL,
appkey: app.globalData.APPKEY,
token: this.data.token
})
st.on("started", (msg)=> {
console.log("Client recv started")
this.setData({
stResult : msg
})
})
st.on("changed", (msg)=>{
console.log("Client recv changed:", msg)
this.setData({
stResult : msg
})
})
st.on("completed", (msg)=>{
console.log("Client recv completed:", msg)
this.setData({
stResult : msg
})
})
st.on("begin", (msg)=>{
console.log("Client recv sentenceBegin:", msg)
this.setData({
stResult : msg
})
})
st.on("end", (msg)=>{
console.log("Client recv sentenceEnd:", msg)
this.setData({
stResult : msg
})
})
st.on("closed", () => {
console.log("Client recv closed")
})
st.on("failed", (msg)=>{
console.log("Client recv failed:", msg)
this.setData({
stResult : msg
})
})
this.data.st = st
},
/**
* Lifecycle function--Called when the page is first rendered.
*/
onReady: function () {
},
/**
* Lifecycle function--Called when the page is displayed.
*/
onShow: function () {
},
/**
* Lifecycle function--Called when the page is hidden.
*/
onHide: function () {
},
/**
* Lifecycle function--Called when the page is unloaded.
*/
onUnload: function () {
console.log("st onUnload")
this.data.stStart = false
wx.getRecorderManager().stop()
if (this.data.st) {
this.data.st.shutdown()
} else {
console.log("st is null")
}
},
/**
* Page-related event handler function--Listens for user pull-down actions.
*/
onPullDownRefresh: function () {
},
/**
* Event handler for when the page is pulled up to the bottom.
*/
onReachBottom: function () {
},
/**
* Called when the user taps the share button in the top-right corner.
*/
onShareAppMessage: function () {
},
onStStart: async function() {
if (!this.data.st) {
console.log("st is null")
return
}
if (this.data.stStart) {
console.log("st is started!")
return
}
let st = this.data.st
try {
await st.start(st.defaultStartParams())
this.data.stStart = true
} catch (e) {
console.log("start failed:" + e)
return
}
wx.getRecorderManager().start({
duration: 600000,
numberOfChannels: 1,
sampleRate : 16000,
format: "PCM",
frameSize: 4
})
},
onStStop: async function() {
wx.getRecorderManager().stop()
await sleep(500)
if (this.data.stStart && this.data.st) {
try {
console.log("prepare close st")
await this.data.st.close()
this.data.stStart = false
} catch(e) {
console.log("close st failed:" + e)
}
}
}
})