Android SDK
The Android SDK for short sentence recognition converts speech captured by an application into text. This topic describes SDK integration, recognition calls, parameters, callbacks, and troubleshooting.
Prerequisites
Activate Intelligent Speech Interaction and obtain a project Appkey. For more information, see Manage projects.
-
Obtain an NLS token. For more information, see Obtain a token.
ImportantObtain tokens on a server and deliver them to the application over a secure channel. Do not store AccessKey credentials on mobile devices or write tokens or complete authentication parameters to logs.
For server-side parameters and message formats, see Short sentence recognition API reference.
Download and integrate the SDK
To download the SDK and sample project, see Select and download mobile SDKs.
Integrate the SDK
Java
Extract the package and copy the AAR file from the sample project's app/libs directory to the application's app/libs directory. Add the dependency to the application module's build.gradle file:
dependencies {
implementation files('libs/nuisdk-release.aar')
}
Open the sample project in Android Studio to view the short sentence recognition implementation in SpeechRecognizerActivity.java. Replace the project Appkey and token before running the sample.
C++
The package provides shared libraries in android_libs and header files in android_include for Android C++ integration.
Configure permissions
Declare network and microphone permissions in the manifest element of AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
On Android 6.0 and later, request microphone permission at runtime. Create the recording instance after permission is granted.
Configure code obfuscation
If code obfuscation is enabled, add the following rule to proguard-rules.pro:
-keep class com.alibaba.idst.nui.* { *; }
Call sequence
Create
NativeNuiandAudioRecordinstances, and callinitializeto initialize the SDK.Call
setParamsto configure recognition parameters.Call
startDialogto start recognition. Start recording when theSTATE_OPENcallback arrives.Provide audio in
onNuiNeedAudioDataand receive intermediate results inEVENT_ASR_PARTIAL_RESULTcallbacks.Call
stopDialogto end audio input, and wait forEVENT_ASR_RESULTor an error callback. With online VAD enabled, the server can detect the end of speech automatically. To cancel the task, callcancelDialog.Call
releasewhen the SDK is no longer needed.
Use the same NativeNui instance for initialization, parameter configuration, and recognition control. Create an instance with new NativeNui() or obtain the singleton with NativeNui.GetInstance().
Code example
The following Java example uses SDK 2.7.4 to recognize 16 kHz, 16-bit, mono PCM audio captured from the microphone. After microphone permission is granted, initialize ShortSentenceRecognizer with the project Appkey, a valid token, and a device ID. Use start, stop, cancel, and release to control recognition.
Call these methods sequentially on a non-UI thread. Switch to the UI thread to update the interface from a callback. Do not call SDK methods directly from SDK callbacks because this can cause a deadlock.
Use the following address for endpoint:
wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import com.alibaba.idst.nui.AsrResult;
import com.alibaba.idst.nui.Constants;
import com.alibaba.idst.nui.INativeNuiCallback;
import com.alibaba.idst.nui.KwsResult;
import com.alibaba.idst.nui.NativeNui;
import org.json.JSONException;
import org.json.JSONObject;
public final class ShortSentenceRecognizer implements INativeNuiCallback {
public interface Listener {
void onResult(String result, boolean isFinal);
void onError(int code, String detail);
}
private static final int SAMPLE_RATE = 16000;
private final NativeNui nui = new NativeNui();
private final Listener listener;
private AudioRecord recorder;
public ShortSentenceRecognizer(Listener listener) {
this.listener = listener;
}
public void initialize(String appkey, String token, String deviceId,
String endpoint, boolean onlineVad) throws JSONException {
int minSize = AudioRecord.getMinBufferSize(SAMPLE_RATE,
AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
if (minSize <= 0) {
throw new IllegalStateException("Unsupported recording configuration");
}
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE,
AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT,
Math.max(minSize * 2, 6400));
if (recorder.getState() != AudioRecord.STATE_INITIALIZED) {
closeRecorder();
throw new IllegalStateException("AudioRecord initialization failed");
}
JSONObject init = new JSONObject();
init.put("app_key", appkey);
init.put("token", token);
init.put("device_id", deviceId);
init.put("url", endpoint);
init.put("service_mode", Constants.ModeAsrCloud);
try {
check(nui.initialize(this, init.toString(),
Constants.LogLevel.LOG_LEVEL_NONE, false));
JSONObject nls = new JSONObject();
nls.put("sample_rate", SAMPLE_RATE);
nls.put("sr_format", "pcm");
nls.put("enable_intermediate_result", true);
nls.put("enable_voice_detection", onlineVad);
if (onlineVad) {
nls.put("max_start_silence", 10000);
nls.put("max_end_silence", 800);
}
JSONObject params = new JSONObject();
params.put("service_type", Constants.kServiceTypeASR);
params.put("nls_config", nls);
check(nui.setParams(params.toString()));
} catch (RuntimeException | JSONException e) {
nui.release();
closeRecorder();
throw e;
}
}
public void start(String refreshedToken) throws JSONException {
JSONObject dialog = new JSONObject();
if (refreshedToken != null && !refreshedToken.isEmpty()) {
dialog.put("token", refreshedToken);
}
check(nui.startDialog(Constants.VadMode.TYPE_P2T, dialog.toString()));
}
public void stop() {
check(nui.stopDialog());
}
public void cancel() {
check(nui.cancelDialog());
}
public void release() {
nui.release();
closeRecorder();
}
private static void check(int code) {
if (code != 0) {
throw new IllegalStateException("NUI error: " + code);
}
}
private void closeRecorder() {
if (recorder != null) {
if (recorder.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING) {
recorder.stop();
}
recorder.release();
recorder = null;
}
}
@Override
public void onNuiAudioStateChanged(Constants.AudioState state) {
if (recorder == null) {
return;
}
if (state == Constants.AudioState.STATE_OPEN) {
recorder.startRecording();
} else if (state == Constants.AudioState.STATE_PAUSE) {
if (recorder.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING) {
recorder.stop();
}
} else if (state == Constants.AudioState.STATE_CLOSE) {
closeRecorder();
}
}
@Override
public int onNuiNeedAudioData(byte[] buffer, int len) {
if (recorder == null || recorder.getState() != AudioRecord.STATE_INITIALIZED) {
return -1;
}
return recorder.read(buffer, 0, len);
}
@Override
public void onNuiEventCallback(Constants.NuiEvent event, int resultCode,
int arg2, KwsResult kwsResult, AsrResult asrResult) {
if (event == Constants.NuiEvent.EVENT_ASR_RESULT
|| event == Constants.NuiEvent.EVENT_ASR_PARTIAL_RESULT) {
if (asrResult != null) {
listener.onResult(asrResult.asrResult,
event == Constants.NuiEvent.EVENT_ASR_RESULT);
}
} else if (event == Constants.NuiEvent.EVENT_ASR_ERROR
|| event == Constants.NuiEvent.EVENT_MIC_ERROR) {
listener.onError(resultCode, asrResult == null ? "" : asrResult.asrResult);
}
}
@Override
public void onNuiAudioRMSChanged(float value) {}
@Override
public void onNuiVprEventCallback(Constants.NuiVprEvent event) {}
}
start(null) does not supply a new token. To update the token, pass a new token to start. After ending audio input normally, wait for a final result or error callback before starting the next recognition task. stop pauses recording for reuse. release releases the SDK and recording resources.
Parameters
Initialization parameters
The parameters argument of initialize is a JSON string.
|
Parameter |
Type |
Description |
|
|
String |
Required. The project Appkey. |
|
|
String |
Required. The NLS token. |
|
|
String |
Required. A device ID. Use a unique ID to help identify the device during troubleshooting. |
|
|
String |
The service endpoint. Use the gateway address provided in the code example. |
|
|
Integer |
Required. Set to |
|
|
String |
The SDK working directory, which must be readable and writable. This parameter can be omitted for online-only short sentence recognition in SDK 2.7.4. For SDK features that depend on resource files, prepare the resources as required by the feature. |
|
|
String |
The directory for debugging files. If log or audio saving is enabled, ensure that this directory is writable and clean up the files regularly. |
|
|
String |
Set to |
The level argument of initialize specifies the logging level. A smaller value produces more log output. The save_log argument specifies whether to save logs to files. The example disables log saving to avoid continuous storage consumption.
Recognition parameters
Call setParams after initialize and before startDialog. Set the top-level service_type to Constants.kServiceTypeASR and place recognition parameters in the nls_config object.
|
Parameter |
Type |
Description |
|
|
Integer |
The audio sample rate, such as |
|
|
String |
The audio transmission format: |
|
|
Boolean |
Whether to return intermediate recognition results. |
|
|
Boolean |
Whether to add punctuation. |
|
|
Boolean |
Whether to enable online VAD to detect the start and end of speech automatically. |
|
|
Integer |
The maximum initial silence duration for online VAD, in milliseconds. The example uses |
|
|
Integer |
The maximum trailing silence duration for online VAD, in milliseconds. The example uses |
The 01B SDK does not include a local VAD module. To use online VAD, set enable_voice_detection to true and continue to use Constants.VadMode.TYPE_P2T in startDialog.
Input audio supports sample rates of 8 kHz and 16 kHz, corresponding to sample_rate values of 8000 and 16000. The sample rate must match the project model.
The following optional parameters also belong in nls_config:
|
Parameter |
Type |
Description |
|
|
Boolean |
Whether to enable inverse text normalization. |
|
|
String |
The custom model ID. |
|
|
String |
The hotword vocabulary ID. |
|
|
Object |
Extended configuration for parameters supported by the server but not listed separately in the SDK. Parameters must meet the server-side requirements. |
When using HTTPDNS, set direct_ip in the top-level parameters of setParams.
For more parameters and value requirements, see Short sentence recognition API reference.
SDK methods and callbacks
Control methods
|
Method |
Description |
|
|
Initializes the SDK. Do not call this method on the UI thread. Release existing resources before initializing the same instance again. |
|
|
Sets parameters in JSON format. |
|
|
Starts recognition. Use |
|
|
Ends audio input. The final result or error is delivered through a callback. |
|
|
Cancels recognition without waiting for a final result. |
|
|
Releases SDK resources. |
|
|
Returns the SDK version. |
Methods that return int use 0 to indicate a successful call and a nonzero value to indicate an error.
For error codes and solutions, see Error code reference.
Callbacks
|
Callback |
Description |
|
|
Notifies the application of the recording state. Start recording on |
|
|
Fills |
|
|
Reports recognition events. |
|
|
Reports audio energy in the range of -160 to 0, which can be used for audio visualizations. |
|
|
A voiceprint-related callback. The short sentence recognition example provides an empty implementation. |
AsrResult.asrResult contains recognition results or error information and a task_id. Record the task ID for troubleshooting. SDK versions that support allResponse provide the complete JSON response in that field. Check that the result object and field are not empty before reading them.
Events
|
Event |
Description |
|
|
The start of speech is detected. |
|
|
The end of speech is detected. |
|
|
An intermediate recognition result. |
|
|
The final recognition result. |
|
|
A recognition error. Check the error code and error information. |
|
|
No audio has been received for two consecutive seconds. Check microphone permission, the recording state, and whether another application is using the recording device. |
|
|
No handling is required in this example. |
FAQ
Can I pass OPUS audio to the SDK?
The SDKs for short sentence recognition and real-time speech recognition accept PCM-encoded, 16-bit, mono audio. sr_format controls the transmission format. When it is set to opus, the SDK encodes and compresses the PCM input before transmission to reduce bandwidth consumption.
Recording file recognition (fast version) supports OPUS audio files. Its file input requirements differ from those of short sentence recognition.
Why does the demo crash when short sentence recognition starts in an emulator, although speech synthesis works?
Emulator environments may have compatibility issues. Use a physical device to troubleshoot.
What should I do if audio callbacks continue without recognition results and error 50000000 follows?
50000000 indicates a service error and may be related to an abnormal SDK runtime state. Collect the complete Logcat output from SDK initialization to the error. Remove credentials and other sensitive information before sharing the logs.
How do I resolve the "audio recoder not init" message?
Check microphone permission and the initialization state of AudioRecord, and ensure that another application is not using the audio module. Call startRecording() before reading data. Successful initialization does not mean recording has started. Run the recording code separately to check whether it can capture audio. The code example starts recording on STATE_OPEN and stops recording on STATE_PAUSE.
Why does initialization return 240021 even though microphone permission is granted?
240021 (FILE_ACCESS_FAIL) indicates a file access failure. Check read and write permissions for the configured directories. If the feature requires SDK resource files, copy them to the working directory. The sample project copies resources as follows:
if (!CommonUtils.copyAssetsData(this)) {
Log.e(TAG, "Failed to copy SDK assets");
return;
}
CommonUtils is a helper class in the sample project. When resource files are required, use CommonUtils.getModelPath(this) to obtain the working directory and pass it as the workspace initialization parameter.