Android SDK

Updated at:

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.

    Important

    Obtain 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

  1. Create NativeNui and AudioRecord instances, and call initialize to initialize the SDK.

  2. Call setParams to configure recognition parameters.

  3. Call startDialog to start recognition. Start recording when the STATE_OPEN callback arrives.

  4. Provide audio in onNuiNeedAudioData and receive intermediate results in EVENT_ASR_PARTIAL_RESULT callbacks.

  5. Call stopDialog to end audio input, and wait for EVENT_ASR_RESULT or an error callback. With online VAD enabled, the server can detect the end of speech automatically. To cancel the task, call cancelDialog.

  6. Call release when 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

app_key

String

Required. The project Appkey.

token

String

Required. The NLS token.

device_id

String

Required. A device ID. Use a unique ID to help identify the device during troubleshooting.

url

String

The service endpoint. Use the gateway address provided in the code example.

service_mode

Integer

Required. Set to Constants.ModeAsrCloud for short sentence recognition.

workspace

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.

debug_path

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.

save_wav

String

Set to "true" to save audio for debugging. Also set the save_log argument of initialize to true and configure a writable debug_path.

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

sample_rate

Integer

The audio sample rate, such as 16000. It must match the input audio and project model.

sr_format

String

The audio transmission format: pcm or opus. Input audio must still be PCM. If opus is selected, the SDK compresses the audio before transmission.

enable_intermediate_result

Boolean

Whether to return intermediate recognition results.

enable_punctuation_prediction

Boolean

Whether to add punctuation.

enable_voice_detection

Boolean

Whether to enable online VAD to detect the start and end of speech automatically.

max_start_silence

Integer

The maximum initial silence duration for online VAD, in milliseconds. The example uses 10000.

max_end_silence

Integer

The maximum trailing silence duration for online VAD, in milliseconds. The example uses 800.

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

enable_inverse_text_normalization

Boolean

Whether to enable inverse text normalization.

customization_id

String

The custom model ID.

vocabulary_id

String

The hotword vocabulary ID.

extend_config

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

int initialize(INativeNuiCallback callback, String parameters, Constants.LogLevel level, boolean save_log)

Initializes the SDK. Do not call this method on the UI thread. Release existing resources before initializing the same instance again.

int setParams(String params)

Sets parameters in JSON format.

int startDialog(Constants.VadMode vad_mode, String dialog_params)

Starts recognition. Use TYPE_P2T. A new token can be supplied in dialog_params.

int stopDialog()

Ends audio input. The final result or error is delivered through a callback.

int cancelDialog()

Cancels recognition without waiting for a final result.

int release()

Releases SDK resources.

String GetVersion()

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

onNuiAudioStateChanged(AudioState state)

Notifies the application of the recording state. Start recording on STATE_OPEN, pause on STATE_PAUSE, and release recording resources on STATE_CLOSE.

int onNuiNeedAudioData(byte[] buffer, int len)

Fills buffer with audio and returns the actual number of bytes written, up to len. A negative return value indicates an error. 0 indicates that no data is currently available. Two consecutive seconds without audio trigger EVENT_MIC_ERROR.

onNuiEventCallback(NuiEvent event, int resultCode, int arg2, KwsResult kwsResult, AsrResult asrResult)

Reports recognition events. resultCode is the error code for error events. arg2 is reserved. kwsResult is a wake-up result that is not used by this feature. asrResult contains the recognition result or error information.

onNuiAudioRMSChanged(float value)

Reports audio energy in the range of -160 to 0, which can be used for audio visualizations.

onNuiVprEventCallback(NuiVprEvent event)

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

EVENT_VAD_START

The start of speech is detected.

EVENT_VAD_END

The end of speech is detected.

EVENT_ASR_PARTIAL_RESULT

An intermediate recognition result.

EVENT_ASR_RESULT

The final recognition result.

EVENT_ASR_ERROR

A recognition error. Check the error code and error information.

EVENT_MIC_ERROR

No audio has been received for two consecutive seconds. Check microphone permission, the recording state, and whether another application is using the recording device.

EVENT_DIALOG_EX

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.