Real-time Speech Recognition Java SDK Integration Guide

Updated at:

This guide shows Java developers how to integrate real-time speech recognition using the ConvAI Voice SDK. It covers recognizing speech from audio files and microphones, handling intermediate and final results, configuring hotwords and context, terminating sessions, and handling errors.

Supported versions

  • JDK: 8 or later

  • SDK: com.aliyun.convai:convai-voice-sdk:0.1.1 or later (Version 0.1.0 does not include the ASR capability)

  • Protocol: WebSocket (The SDK manages this protocol, so you do not need to build protocol frames manually.)


1. Prerequisites

Prepare the following:

  1. API Key: An API Key from Voice Studio, in the format sk-xxxxxxxx. This key is also used for real-time speech synthesis. You can create an API Key in the console.

  2. Recognition model: This guide uses Qwen-Audio-ASR-VoicePica (SDK constant AsrModels.QWEN_AUDIO_ASR_VOICEPICA).

  3. Audio: Confirm the audio format and sample rate. We recommend mono channel, 16-bit, little-endian PCM with a sample rate of 16,000 Hz.

1.1 Endpoint

wss://convai-platform.aliyuncs.com/api-ws/v1/convai-asr/inference

The SDK uses this endpoint by default, so you do not need to call endpoint(). Automatic Speech Recognition (ASR) and Text-to-Speech (TTS) use different endpoints and clients:

Feature

Client

Endpoint path

real-time speech recognition

AsrRealtimeClient

/api-ws/v1/convai-asr/inference

real-time speech synthesis

VoiceRealtimeClient

/api-ws/v1/inference

1.2 Maven dependency

Add the following to your pom.xml file:

<dependency>
    <groupId>com.aliyun.convai</groupId>
    <artifactId>convai-voice-sdk</artifactId>
    <version>0.1.1</version>
</dependency>

<!-- Optional: The SDK uses slf4j-api. You can choose your own logging implementation. -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>2.0.6</version>
    <scope>runtime</scope>
</dependency>

2. Core SDK objects

Object

Description

Recommendation

AsrRealtimeClient

Manages authentication, WebSocket connections, the connection pool, heartbeats, and reconnection.

A heavyweight object. We recommend creating a single instance per application process and reusing it globally.

RecognitionOptions

Describes the model, audio format, sample rate, and recognition parameters for a recognition task.

An immutable object. Reuse it when the configuration is the same.

RecognitionSession

Represents a recognition session for a single audio stream.

Create one for each audio stream. The write() and finish() methods must be called by a single producer thread.

RecognitionListener

Receives intermediate results, final results, and task events.

In the callback, do only quick work or enqueue the data.

RecognitionSentence

An intermediate or final recognition result.

Use isFinal() to distinguish between them.

RecognitionResult

The final result of the session, containing all final sentences, audio usage, and the link ID.

Returned by finish() or recognize().

Recommended call flow:

Create a global AsrRealtimeClient
        ↓
Create a RecognitionSession for an audio stream
        ↓
Call write(audio) multiple times. The SDK returns recognition results in a stream.
        ↓
Call finish() to wait for the final recognition results.
        ↓
Close the session
        ↓
Close the client when the application exits

3. Quick start: Recognize a local PCM file

The following example uses recognize() to recognize a local PCM file. It prints intermediate and final results, and outputs the full text after the recognition completes.

import com.convai.voice.sdk.asr.AsrFormat;
import com.convai.voice.sdk.asr.AsrModels;
import com.convai.voice.sdk.asr.AsrRealtimeClient;
import com.convai.voice.sdk.asr.RecognitionListener;
import com.convai.voice.sdk.asr.RecognitionOptions;
import com.convai.voice.sdk.asr.RecognitionResult;
import com.convai.voice.sdk.asr.RecognitionSentence;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

public class FileRecognitionExample {

    public static void main(String[ ] args) throws Exception {

        RecognitionOptions options = RecognitionOptions.builder()
                .model(AsrModels.QWEN_AUDIO_ASR_VOICEPICA)
                .format(AsrFormat.PCM)
                .sampleRate(16000)
                .build();

        AsrRealtimeClient client = AsrRealtimeClient.builder()
                .apiKey(System.getenv("CONVAI_API_KEY"))
                .build();
        try (InputStream audio = Files.newInputStream(Paths.get(System.getenv("CONVAI_ASR_AUDIO")))) {
            RecognitionResult result = client.recognize(options, audio, new RecognitionListener() {
                public void onSentence(RecognitionSentence sentence) {
                    System.out.println((sentence.isFinal() ? "[Final] " : "[Intermediate] ") + sentence.text());
                }
            });

            System.out.println("Full text=" + result.text());
            System.out.println("Audio duration (seconds)=" + result.durationSeconds());
            for (RecognitionResult.Segment segment : result.segments()) {
                System.out.println("taskId=" + segment.taskId()
                        + " taskUuid=" + segment.taskUuid()
                        + " requestId=" + segment.requestId());
            }
        } finally {
            client.close();
        }
    }
}

Setup

Save the code as src/main/java/FileRecognitionExample.java in your Maven project. For a new project, add the following properties to the <project> tag in your pom.xml file. If your project is already configured for Java 8 or later, you can use your existing configuration:

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

From your project's root directory, where pom.xml is located, run the following commands:

export CONVAI_API_KEY="sk-your-VoiceStudio-API-key"
export CONVAI_ASR_AUDIO="/path/to/audio.pcm"
mvn -q compile org.codehaus.mojo:exec-maven-plugin:3.1.0:java \
  -Dexec.mainClass=FileRecognitionExample

Notes

  • The recognize() method supports only the PCM and WAV formats and sends audio at 1x speed. Therefore, the processing time is approximately equal to the audio's duration. Sending an entire audio file at once may cause a server-side backlog overflow.

  • The recognize() method does not close the provided InputStream; the caller is responsible for closing it.

  • This example uses a raw PCM file. Do not simply rename a WAV file with a .pcm extension. When recognizing a WAV file, set format(AsrFormat.WAV). The file must be 16-bit PCM encoded and mono. The specified sample rate must match the actual sample rate of the WAV file.


4. Full parameter list

4.1 AsrRealtimeClient.Builder client parameters

Builder method

Required

Default

Support status and constraints

endpoint(String) / endpoint(URI)

No

wss://convai-platform.aliyuncs.com/api-ws/v1/convai-asr/inference

Only ws and wss are supported. The path must end with /api-ws/v1/convai-asr/inference.

apiKey(String)

One of the two

None

A fixed API key. Do not hardcode it in your code or commit it to a code repository.

apiKeyProvider(ApiKeyProvider)

One of the two

None

Ideal for use with a configuration center or temporary credential. If a credential expires (HTTP 401 / close code 4401), the SDK calls refresh() once. If this call returns a new credential, the SDK re-establishes the connection. An HTTP 403 / close code 4403 error does not trigger a refresh.

userAgent(String)

No

convai-voice-sdk-java

Set this to your application name and version to aid server-side troubleshooting.

requestIdPrefix(String)

No

asr-java-

For each handshake, an X-Request-Id is automatically generated in the format: prefix + a UUID without hyphens. If you pass null, the ID is not generated.

header(String, String)

No

None

Adds a custom handshake request header. You cannot set the Authorization header.

connectTimeoutMillis(long)

No

10000

The WebSocket connection setup timeout, in milliseconds.

taskStartTimeoutMillis(long)

No

10000

The timeout for waiting for task start confirmation, in milliseconds.

finishTimeoutMillis(long)

No

60000

The maximum time in milliseconds that finish() waits for the final results and task completion.

pacing(boolean)

No

true

Sends PCM/WAV audio at 1x speed. Disable this only if your application already sends audio in a strict real-time cadence.

guards(GuardPolicy)

No

Idle reclamation: 45 seconds. Audio pause protection: 15 seconds. Heartbeat: 20 seconds.

Protection for idle connections, audio pauses, and heartbeats. We recommend keeping the default settings in production.

reconnect(ReconnectPolicy)

No

ReconnectPolicy.defaults()

The retry backoff policy for connection and task startup failures.

Default protection policies:

  • WebSocket heartbeat: 20 seconds.

  • Idle connection reclamation: 45 seconds. Idle connections still consume your concurrency quota.

  • Audio pause protection: 15 seconds. If write() is not called for more than 15 seconds, the SDK gracefully ends the current task. For more details, see Section 8.

  • Maximum connection setup attempts: 5, using a random exponential backoff.

Note: The default pause protection value for GuardPolicy.defaults() is 18 seconds, which is intended for TTS. When customizing guards() for ASR, explicitly set the ASR pause protection time. For example: GuardPolicy.defaults().idleCloseMillis(30000L).pauseGuardMillis(15000L).

4.2 RecognitionOptions.Builder recognition parameters

Builder method

Required

Default

Support status and constraints

model(String)

Yes

None

AsrModels.QWEN_AUDIO_ASR_VOICEPICA

format(AsrFormat)

No

PCM

PCM / WAV / OPUS

sampleRate(int)

No

16000

The model in this guide supports 8000 or 16000 Hz. The value must match the actual audio sample rate. The SDK does not perform resampling.

hotword(String, int)

No

None

Adds a task-level hotword. The weight must be in the range [1, 5]. A single hotword cannot exceed 20 characters.

hotwords(Map<String,Integer>)

No

Empty

Sets multiple task-level hotwords at once. You can specify up to 1,024 hotwords. A single hotword cannot exceed 20 characters.

languageHints(String...)

No

Empty

For the model in this guide, only the first item in the list is effective, and it should be zh. We recommend passing languageHints("zh"). If left empty, the parameter is not sent, and the engine determines the language.

maxSentenceSilence(Integer)

No

Not sent

The VAD silence threshold for sentence splitting, in milliseconds. The value must be in the range [200, 6000].

speechNoiseThreshold(Double)

No

Not sent

The VAD threshold for distinguishing speech from noise. The value must be in the range [-1.0, 1.0].

specialWordFilter(String)

No

Not sent

The sensitive word filtering configuration. The value must be a string that represents a JSON object. For details, see Section 7.3, "Sensitive word filtering."

context(List<ContextMessage>)

No

Empty

The initial context, encoded as payload.input.context. When providing context, pass only the most recent message. For an example, see Section 7.2.

parameter(String, Object)

No

None

A pass-through for new parameters not yet explicitly supported by the SDK. This method is ignored if the parameter name conflicts with one already managed by the SDK.

Note: Parameters are validated locally when newSession() or recognize() is called. If validation fails, an InvalidOptionException is thrown. For the model used in this guide, the SDK only checks that the sample rate is a positive integer. The language list is sent as is, without validating the supported range or truncating it to the first item. Passing local validation does not guarantee that other sample rates or languages are supported. In the context list, neither the message objects nor their text content can be null.

4.3 Audio format requirements

Format

Requirements

SDK sending method

Recommended scenarios

PCM

Mono, 16-bit, little-endian, with no file header.

Sent at 1x speed, in frames of approximately 100 ms.

Microphone, telephony, or RTC real-time audio.

WAV

PCM16 (16-bit) encoded, mono. The file header is sent only once at the beginning of the audio stream.

Sent at 1x speed, in frames of approximately 100 ms.

Complete audio files.

OPUS

Ogg encapsulation.

Sent in 16 KB chunks, with no throttling.

Bandwidth-constrained scenarios.

Audio notes:

  • The duration of PCM audio is calculated as total byte count / 2 / sample rate. For example, 16,000 Hz PCM audio is 32,000 bytes per second.

  • 8 kHz telephony audio should be recognized at 8,000 Hz. Do not upsample it to 16,000 Hz.

  • The duration of compressed audio cannot be calculated from its byte count, so the SDK does not apply throttling. Your application must control the write() cadence based on the actual audio duration.


5. SDK method reference

5.1 AsrRealtimeClient

Method

Description

newSession(options, listener)

Creates a streaming recognition session. A connection is established on the first call to write() or start().

recognize(options, audio)

Recognizes a PCM or WAV input stream. This blocking call waits until the recognition is complete.

recognize(options, audio, listener)

Same as above, but also triggers callbacks for intermediate and final results.

close()

Closes all sessions, the connection pool, and background threads. Call this method when the application exits.

5.2 RecognitionSession

Method

Description

start()

Establishes a connection and starts a task in advance. Use this to verify your credential, permissions, and concurrency quota before stream pushing. This is typically not required.

write(byte[])

Sends audio data. Can be called multiple times.

write(byte[], int, int)

Sends a segment of an audio array. Can be called multiple times.

updateContext(List<ContextMessage>)

Replaces the context. A non-empty context is sent dynamically while a task is running, without an update acknowledgment. If the task has not started or has already finished, the context is applied to the next task.

finish()

Ends the session gracefully, waiting for the final results and for the current task to reach the task-finished success state. This process does not rely on additional Ping/Pong acknowledgments. It throws an exception if the task fails or is interrupted. For more information, see Section 10.3.

close()

Ends and releases the session. It aborts any in-progress task without waiting for the final results. It preserves the results of tasks that have already reached a success state.

Calling constraints:

  • write() accepts audio of any length, and the SDK splits it into frames. For PCM and WAV, throttling is enabled by default, and write() can block.

  • If you write an odd number of bytes of PCM data, the SDK buffers the last byte and prepends it to the next write.

  • The same producer thread must call the start(), write(), updateContext(), and finish() methods sequentially.

  • The finish() method closes the session regardless of whether it succeeds or throws an exception. You cannot call write() or updateContext() afterward. Calling finish() again after it succeeds returns the same result and does not re-trigger the completion callback.

  • The close() method can be called from any thread. It is suitable for abort scenarios, such as when a user hangs up or closes a page.

5.3 RecognitionListener

Callback

Execution thread

Description

onSentence(RecognitionSentence)

WebSocket read thread

Called for both intermediate and final results.

onTaskStarted(String taskId, String taskUuid)

The thread that calls write() or start()

Triggered when an upstream task starts successfully. The SDK may trigger this callback multiple times if it automatically splits tasks.

onSegmentFinished(RecognitionResult.Segment)

The thread that ends the task

Triggered when an upstream task finishes normally. If the audio pause protection mechanism finishes the task, the SDK may execute this callback on a background thread.

The SDK logs any exceptions thrown in a callback at the WARN level and then ignores them. They do not interrupt the recognition process.


6. Scenario 2: Real-time microphone recognition

The following example uses Java Sound, which is included in JDK 8, to capture 16,000 Hz, 16-bit, little-endian, mono PCM audio and perform continuous recognition for 10 seconds. The example uses intermediate results for real-time subtitles and passes the final results to a downstream service.

import com.convai.voice.sdk.asr.AsrFormat;
import com.convai.voice.sdk.asr.AsrModels;
import com.convai.voice.sdk.asr.AsrRealtimeClient;
import com.convai.voice.sdk.asr.RecognitionListener;
import com.convai.voice.sdk.asr.RecognitionOptions;
import com.convai.voice.sdk.asr.RecognitionResult;
import com.convai.voice.sdk.asr.RecognitionSentence;
import com.convai.voice.sdk.asr.RecognitionSession;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;

public class MicrophoneRecognitionExample {

    public static void main(String[ ] args) throws Exception {

        final int sampleRate = 16000;
        AudioFormat pcm16 = new AudioFormat(sampleRate, 16, 1, true, false);
        RecognitionOptions options = RecognitionOptions.builder()
                .model(AsrModels.QWEN_AUDIO_ASR_VOICEPICA)
                .format(AsrFormat.PCM)
                .sampleRate(sampleRate)
                .build();

        RecognitionListener listener = new RecognitionListener() {
            public void onSentence(RecognitionSentence sentence) {
                if (sentence.isFinal()) {
                    // In a real-world application, enqueue the final result and pass it to an LLM or a business logic thread for processing.
                    System.out.println("\n[Final] " + sentence.text());
                } else {
                    // Intermediate results for the same sentenceId are continuously updated, so you should overwrite them.
                    System.out.print("\r[Intermediate " + sentence.sentenceId() + "] " + sentence.text());
                }
            }

            public void onTaskStarted(String taskId, String taskUuid) {
                System.out.println("Task started. taskId=" + taskId + ", taskUuid=" + taskUuid);
            }
        };


        byte[ ] buffer = new byte[sampleRate * 2 / 10]; // 100 ms

        try (AsrRealtimeClient client = AsrRealtimeClient.builder()
                     .apiKey(System.getenv("CONVAI_API_KEY")).build();
             TargetDataLine microphone = (TargetDataLine) AudioSystem.getLine(
                     new DataLine.Info(TargetDataLine.class, pcm16));
             RecognitionSession session = client.newSession(options, listener)) {
            microphone.open(pcm16, buffer.length * 4);
            session.start();
            microphone.start();
            long startedAt = System.nanoTime();
            while (System.nanoTime() - startedAt < 10_000_000_000L) {
                int n = microphone.read(buffer, 0, buffer.length);
                if (n > 0) {
                    session.write(buffer, 0, n);
                }
            }
            microphone.stop();
            RecognitionResult result = session.finish();
            System.out.println("Full text=" + result.text());
            System.out.println("Audio duration (seconds)=" + result.durationSeconds());
        }
    }
}

Result handling recommendations:

  • Intermediate result text may be rewritten, and real-time subtitles should be overwritten based on taskId + sentenceId.

  • In a conversational scenario, the result is passed to the downstream service only if isFinal() == true.

  • onSentence() is executed in the WebSocket read thread and should only perform quick processing or enqueue operations. Do not call write() or finish(), execute network requests, or perform long-running blocking operations in the callback.


7. Example 3: Hotwords, context, and sensitive word filtering

7.1 Hotword configuration

To improve the recognition of specific terms, you can pass hotwords directly within a task by using the hotword() or hotwords() method.

RecognitionOptions options = RecognitionOptions.builder()
        .model(AsrModels.QWEN_AUDIO_ASR_VOICEPICA)
        .format(AsrFormat.PCM)
        .sampleRate(16000)
        .hotword("VoicePica", 5)
        .hotword("Voice Studio", 4)
        .build();

Note:

  • The weight for a task-level hotword must be in the range [1, 5]. You can specify up to 1,024 hotwords, and each hotword cannot exceed 20 characters.

  • Hotwords only increase the recognition probability of the specified words and do not guarantee that they will appear in the recognition result.

7.2 Initial context and dynamic updates

VoicePica supports both an initial context and dynamic updates during a task. When using context, provide only the most recent message, not the entire conversation history. ContextMessage.user(text) represents a user message, and ContextMessage.assistant(text) represents an assistant message.

The following example sets an initial context, updates the context after sending the first PCM audio segment, and then sends the remaining audio to retrieve the result.

import com.convai.voice.sdk.asr.AsrFormat;
import com.convai.voice.sdk.asr.AsrModels;
import com.convai.voice.sdk.asr.AsrRealtimeClient;
import com.convai.voice.sdk.asr.ContextMessage;
import com.convai.voice.sdk.asr.RecognitionListener;
import com.convai.voice.sdk.asr.RecognitionOptions;
import com.convai.voice.sdk.asr.RecognitionResult;
import com.convai.voice.sdk.asr.RecognitionSentence;
import com.convai.voice.sdk.asr.RecognitionSession;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;

public class ContextRecognitionExample {

    public static void main(String[ ] args) throws Exception {

        RecognitionOptions options = RecognitionOptions.builder()
                .model(AsrModels.QWEN_AUDIO_ASR_VOICEPICA)
                .format(AsrFormat.PCM)
                .sampleRate(16000)
                .context(Collections.singletonList(ContextMessage.user("Query last month's orders.")))
                .build();
        RecognitionListener listener = new RecognitionListener() {
            public void onSentence(RecognitionSentence sentence) {
                System.out.println((sentence.isFinal() ? "[Final] " : "[Intermediate] ") + sentence.text());
            }
        };

        try (AsrRealtimeClient client = AsrRealtimeClient.builder()
                     .apiKey(System.getenv("CONVAI_API_KEY")).build();
             InputStream audio = Files.newInputStream(Paths.get(System.getenv("CONVAI_ASR_AUDIO")));
             RecognitionSession session = client.newSession(options, listener)) {

            byte[ ] buffer = new byte[3200];

            int n = audio.read(buffer);
            if (n > 0) {
                session.write(buffer, 0, n);
                session.updateContext(Collections.singletonList(
                        ContextMessage.assistant("Please provide the order ID you want to query.")));
            }
            while ((n = audio.read(buffer)) != -1) {
                if (n > 0) {
                    session.write(buffer, 0, n);
                }
            }
            RecognitionResult result = session.finish();
            System.out.println("Full text=" + result.text());
        }
    }
}

Update Semantics:

  • The context(...) method sets the initial context for the session. The SDK sends this context in the payload.input.context field of the run-task request.

  • During a running task, a non-empty updateContext(...) call sends a continue-task request and replaces the context for all subsequent tasks in that session. If the current task has not started or has already finished, this method only updates the context for the next task and does not start a new task solely for this purpose.

  • The server does not return an acknowledgment for context updates. The updateContext() method does not wait for confirmation. A successful return from the method does not guarantee that the server has applied the new context.

  • Both the initial context and every non-empty update must contain only the most recent message. The SDK does not check the number of messages or trim the list; the caller is responsible for constructing a single-item list. The message object and its text cannot be null.

  • For VoicePica, calling updateContext(null) or passing an empty list only clears the context for subsequent tasks. It does not send an instruction to clear the context for the current task. To ensure the current task stops using the old context, you must end it and create a new session without context.

On Update Failure:

  • If context parameter validation fails, the SDK throws an InvalidOptionException, and the new context does not replace the old one. The UTF-8 size of the complete request JSON must not exceed 64 KiB. The SDK checks the initial context size when encoding the request during the first start() or write() call. The updateContext() method checks the size of dynamic updates as it encodes the request.

  • If a task has already failed or the connection is lost, updateContext() first throws the exception from that task, and does not save the current update. This does not necessarily mean the new context parameters are invalid. After handling the exception, you can call updateContext() again on the same session to set the context for the next task before resuming with write().

  • If an exception occurs while sending the update instruction, the SDK has already saved the new context locally and does not roll it back automatically. Subsequent new PCM tasks may continue to use it. An exception also does not prove that the server did not receive the update. To ensure the next task uses the correct context, set it again after handling the exception or create a new session. For a complete exception handling example, see Section 10.2.

7.3 Sensitive word filtering

Pass the sensitive word filtering configuration as a JSON object string using the specialWordFilter(String) method. You cannot pass a Map or other object types directly. The filter applies to both intermediate and final results.

JSON field

Type

Description

filter_with_signed.word_list

Array[String]

Replaces the words in the list with an equal number of asterisk (*) characters.

filter_with_empty.word_list

Array[String]

Removes the words in the list from the recognition text.

import com.convai.voice.sdk.asr.AsrModels;
import com.convai.voice.sdk.asr.RecognitionOptions;

public class SpecialWordFilterExample {

    public static void main(String[ ] args) {

        RecognitionOptions options = RecognitionOptions.builder()
                .model(AsrModels.QWEN_AUDIO_ASR_VOICEPICA)
                .specialWordFilter("{\"filter_with_signed\":{\"word_list\":[\"example sensitive word\"]},"
                        + "\"filter_with_empty\":{\"word_list\":[\"example word to remove\"]}}")
                .build();
    }
}

The SDK checks if the string is a valid JSON object, but the server handles the internal filtering configuration and its effects. Passing local validation does not guarantee that the filter is active. Please verify the replacement and removal effects on both intermediate and final results by using real audio that contains the example words.


8. Scenario 4: Long silences and audio pauses

An ASR task requires a continuous audio stream. If the write() method is not called for more than 15 seconds, the SDK gracefully ends the current task by default, preserving any final results already returned for that task.

Audio format

Behavior after pause

PCM

The SDK automatically starts a new task on the next write() call. You can continue to use the same RecognitionSession.

WAV / Compressed formats

You cannot resume sending the original audio stream. The next write() call throws a VoiceSdkException. You must create a new session and send the complete audio stream from the beginning.

Recommendations:

  • In microphone or telephony scenarios, you should continuously send the captured audio, including silence segments, to prevent the SDK from segmenting tasks due to pauses.

  • When a user has clearly finished speaking or hangs up, call finish() to retrieve the final results.

  • After automatic segmentation, RecognitionResult.segments() will contain multiple segments. For a segment from an automatically ended task, Segment.autoSegmented() returns true.

  • The RecognitionSentence.beginTime() and endTime() values are relative to the audio start time within their respective task. After the SDK performs automatic segmentation, the timing for the new task restarts from 0.

  • When the server proactively returns the successful final state task-finished for the current task, the SDK also collects the task's final sentences and usage and triggers the onSegmentFinished() callback. A subsequent connection closure does not alter the successful result of that task. For more details, see Section 10.3. If the connection is already closed (including close code 1001 for maintenance), the next PCM write() call re-establishes the connection and starts a new task. For WAV or OPUS, you must still create a new session and send the complete audio stream.


9. Use case 5: Abort recognition

When a user hangs up, navigates away, or stops recognition, and you no longer need the final result, call close() to close the session.

final RecognitionSession session = client.newSession(options, listener);

// The capture thread continuously calls session.write(audio).
// When another thread receives a hang-up or stop event:
session.close();

Differences:

Method

Use case

Final result

finish()

A user finishes speaking, or an audio file has been completely sent.

Waits for and returns the final result.

close()

A user hangs up, closes a page, or your application aborts recognition.

Does not wait for pending final results. The results of tasks that have already reached a final success state are preserved.

ASR has no cancel command. When you call close(), if the current task has not yet reached the task-finished final success state, the SDK aborts the task and closes the connection. This connection is not returned to the connection pool. If the task has already reached a final success state, the SDK preserves its result, and the connection can be returned to the connection pool.


10. Error handling and retries

Business exceptions defined by the SDK inherit from VoiceSdkException and are unchecked exceptions. The SDK might also throw standard Java exceptions. For example, it throws an IllegalStateException for an operation on a closed session, and an UncheckedIOException is thrown if recognize() fails to read the input stream. Do not treat all of these exceptions as server-side failures that require a retry.

Exception

Description

Recommended action

InvalidOptionException

Local parameter validation failed, or the model does not support the current combination of parameters.

Correct the parameters. Do not retry.

AuthFailedException

The API Key is invalid, has expired, or is not authorized.

Check or refresh your credential.

ConcurrencyLimitException

The concurrent connection limit was exceeded, and the request failed despite the SDK's internal retries with backoff.

Reduce concurrency or retry later.

RecognitionFailedException

The server indicated that the recognition task failed.

Check the error code to determine if the operation is retryable.

RecognitionInterruptedException

The connection was interrupted during recognition.

Decide whether to re-recognize based on the final results you have already received.

TransportException

A timeout occurred during connection setup, sending data, or waiting for a response.

Check your network and retry a limited number of times.

VoiceSdkException

WAV or compressed formats cannot be resumed after a task is segmented.

Create a new session and send the audio stream from the beginning.

10.1 Automatic retry scope

The SDK automatically retries an operation only before a recognition task starts and before any audio has been sent. This includes the following cases:

  • The concurrency limit is exceeded.

  • An UPSTREAM_ERROR indicates a connection error with the recognition engine.

  • A SERVICE_DRAINING state indicates that a service instance is being taken offline.

  • The connection is closed normally before the task starts.

If a recognition task with sent audio fails or is interrupted, the SDK does not automatically replay the audio. ASR does not support resumption from breakpoint. To re-recognize, your application must retain the original audio and send it again from the beginning. Re-recognition generates a new taskId. To deduplicate results from replayed audio across different tasks, you should use a business-specific audio identifier and the corresponding audio range, rather than relying solely on taskId and sentenceId.

10.2 RecognitionFailedException error codes

errorCode()

Description

retryable()

CLIENT_ERROR

Protocol usage error, unsupported parameters, audio interval timeout, or upstream buffer overflow.

false

MODEL_NOT_ALLOWED

The model is not activated or you are not authorized to use it.

false

CONFIG_MISSING

A required platform configuration is missing.

false

UPSTREAM_ERROR

A connection error occurred with the recognition engine.

true

SERVICE_DRAINING

The task was interrupted because a service instance was taken offline.

true

UNKNOWN

Other error codes passed through from the recognition engine. See rawErrorCode() for the original value.

false

Recommended error handling code:

The following example uses the client, options, listener, and imports from the preceding section. It reads a PCM file and places all operations, including session creation, startup, stream pushing, context update, and termination, within the same exception handling block. The client is managed by the caller, while the input stream and the session are automatically closed by the example.

try (InputStream audio = Files.newInputStream(Paths.get(System.getenv("CONVAI_ASR_AUDIO")));
     RecognitionSession session = client.newSession(options, listener)) {
    session.start();
    session.updateContext(Collections.singletonList(
            ContextMessage.assistant("Please provide the order number you want to query.")));

    byte[ ] buffer = new byte[3200];

    int n;
    while ((n = audio.read(buffer)) != -1) {
        if (n > 0) {
            session.write(buffer, 0, n);
        }
    }
    RecognitionResult result = session.finish();
    System.out.println("Full text=" + result.text());
} catch (com.convai.voice.sdk.error.RecognitionFailedException e) {
    System.err.println("errorCode=" + e.rawErrorCode());
    System.err.println("errorMessage=" + e.errorMessage());
    System.err.println("taskId=" + e.taskId());
    System.err.println("taskUuid=" + e.taskUuid());
    System.err.println("requestId=" + e.requestId());
    System.err.println("Audio usage for failed task (seconds)=" + e.durationSeconds());
    System.err.println("Retryable=" + e.retryable());
} catch (com.convai.voice.sdk.error.RecognitionInterruptedException e) {
    System.err.println("closeCode=" + e.rawCloseCode());
    System.err.println("taskId=" + e.taskId());
    System.err.println("requestId=" + e.requestId());
    System.err.println("Number of final sentences received=" + e.finalSentences());
} catch (com.convai.voice.sdk.error.InvalidOptionException e) {
    System.err.println("Invalid parameters. Fix them and try again: " + e.getMessage());
} catch (com.convai.voice.sdk.error.VoiceSdkException e) {
    System.err.println("Recognition call failed: " + e.getMessage());
} catch (java.io.IOException e) {
    System.err.println("Failed to read audio: " + e.getMessage());
}

If a failure occurs during a running task, the SDK throws an exception on the next call to start(), write(), updateContext(), or finish(). The failure is not necessarily caused by the parameters of that call. In the example above, the session is closed upon exiting the try block, so you must create a new session to re-recognize after an error. The retryable flag is only an error classification and does not mean the SDK will replay audio. Your application must still retain the original audio, limit the number of retries, and use a backoff strategy.

If your application manages a still-open PCM session and an exception is thrown by start(), write(), or updateContext(), you can continue to call write() to start a new task after handling the RecognitionFailedException or RecognitionInterruptedException. The SDK will not resend audio for which the failed task returned no result. If the exception is thrown by finish(), the session is already closed, and you must create a new session to re-recognize.

10.3 Task completion and connection closure

The SDK considers a recognition task successful when it receives the task-finished state. It no longer sends an extra Ping message for completion acknowledgment or waits for an extra Pong. The normal WebSocket heartbeat mechanism remains unchanged.

  • After a final success state is received, a subsequent remote closure (including close codes 1000, 1001, or 1011) does not invalidate the task's successful result. The final sentences, usage at the final state, and link IDs in the Segment are all preserved. This closure does not throw a recognition interruption exception.

  • The connection pool reuses only connections that are still open and have no task listeners. Closed connections are not returned to the connection pool. Subsequent recognition attempts will establish new connections, including reconnections after a maintenance closure (code 1001).

  • If the SDK receives a task-failed state first, it still throws a RecognitionFailedException. If the connection is lost before a final success state is reached, the SDK still throws an exception according to the existing interruption semantics. The close code itself does not prove that the task succeeded.

  • A call to close() from your application does not wait for final results and cannot replace the task-finished final success state. Results from tasks that have already succeeded are preserved. For more information, see Section 9.


11. Results and observability

11.1 RecognitionResult

Method

Description

text()

Concatenates the text of all final sentences in order.

sentences()

Returns all final sentences, excluding intermediate results.

segments()

Returns the results of all successfully finalized tasks, excluding failed tasks.

durationSeconds()

The sum of the final-state audio usage from all successful segments, in seconds. Returns null if the usage for any successful segment is unavailable.

Usage metrics:

  • This metric represents the total amount of audio, including silence, that the platform has successfully sent to the recognition engine. The duration of each task is rounded to the nearest second (half up). The SDK directly sums the final-state values from each successful segment without re-rounding.

  • For example, if two tasks are each 2.5 seconds long, they are individually rounded to 3 seconds, and the total is 6 seconds. The durations are not summed to 5 seconds before rounding.

  • Failed tasks are not included in segments(). The final-state usage from a failed task is provided by RecognitionFailedException.durationSeconds(). This value is null if the usage is unavailable.

  • Audio usage is not a confirmation of successful billing, and the sum of successful segments does not equal the final bill. Aborted or disconnected sessions, or sessions where final usage is not received, do not mean the service is free. Charges are based on the service agreement and the final bill.

Each Segment object provides the following:

Method

Description

taskId()

The client-generated task ID.

taskUuid()

The task ID from the recognition engine. May be null.

requestId()

The X-Request-Id from the handshake request header.

durationSeconds()

The final-state audio usage for this task, in integer seconds. A null value indicates that the metric is unavailable and does not mean zero.

audioBytes()

The actual number of audio bytes sent for this task.

autoSegmented()

Indicates whether the task was ended by pause protection or explicitly by the server.

11.2 RecognitionSentence

Method

Description

taskId()

The task ID to which the result belongs.

sentenceId()

The sentence ID, which increments from 1 within each task.

text()

The recognized text, including punctuation. May be an empty string.

isFinal()

true for a final result; false for an intermediate result.

sentenceBegin()

Indicates whether this is the first result for a sentence.

beginTime() / endTime()

The start and end times of the sentence, in milliseconds. The endTime() for an intermediate result is null.

words()

The word-level results for the sentence. Note that this list contains at most one item. Timestamps are at the sentence level; word-level or character-level timestamps are not provided. Trailing punctuation is placed in punctuation(). Returns an empty list if no result is available.

channelId() / speakerId()

For the model used in this guide, the channel ID is fixed at 0, and the speaker ID is always null.

durationSeconds()

A snapshot of the cumulative audio usage up to this result. These values should not be summed.

The RecognitionWord object provides text(), punctuation(), beginTime(), endTime(), fixed(), and speakerId(). Timestamps are measured in milliseconds and are relative to the start of the audio for the corresponding task. For the model used in this guide, speakerId() is always null.

About multiple task IDs:

To prevent timeouts due to audio pauses, the SDK may split a single recognition session into multiple upstream tasks. Therefore, it is normal for segments().size() to be greater than 1. The sentenceId() is renumbered for each task and must be combined with the taskId() for unique identification.


12. Connection and concurrency best practices

  1. Create only one AsrRealtimeClient instance per application process. Do not create a new instance for each recognition.

  2. Create a new RecognitionSession for each audio stream. Do not make concurrent calls to the write() or finish() methods on the same session from different threads.

  3. To end a session normally, call finish() and wait for it to return the final results. Do not use close() as a substitute for waiting for the task to finish.

  4. To abort recognition, call close(). Always close a session after use to release the connection.

  5. Use the callback thread for quick processing or enqueueing only. Offload time-consuming operations, such as LLM calls, database writes, or uploads, to a separate thread.

  6. Keep the default throttling for PCM and WAV audio. Disable pacing only if your application is already sending audio in a strict real-time cadence.

  7. Both concurrent sessions and idle connections consume your concurrency quota. If you exceed your limit, avoid aggressive retries.

  8. Do not embed an API key in a client installation package, browser-side code, logs, or a code repository. Instead, inject the API key through a server-side configuration or a key management system.


13. FAQ

13.1 Empty or garbled recognition results

Ensure that your audio parameters match the recognition parameters:

  • PCM audio is mono, 16-bit signed, and little-endian.

  • The sampleRate() is set to 8000 or 16000 as required by the model, and must match the actual sample rate of your audio.

  • Raw PCM does not include a WAV file header.

  • WAV files use AsrFormat.WAV and must be 16-bit PCM encoded and mono.

13.2 Recognition time close to audio duration

By default, the SDK sends PCM and WAV audio at 1x speed to prevent server backlog overflow, meaning a one-minute audio file takes about one minute to send.

13.3 Multiple results for one sentence

During the recognition process, the service first returns an intermediate result, followed by the final result. The intermediate result may be overwritten. The final result is the one where isFinal() == true.

13.4 Multiple task IDs

If write() is not called for more than 15 seconds, the SDK gracefully ends the current task. For PCM audio, the next write() call starts a new task. The SDK aggregates the final results from all tasks in segments().

13.5 Why is audio usage null?

A null value indicates that the server did not return the final usage or that metering is unavailable. It does not mean the audio usage is zero. Do not sum the values from RecognitionSentence.durationSeconds(), as these values represent a cumulative snapshot, not an increment.

13.6 Reporting an issue

Please provide the following information:

  1. The exact time the issue occurred.

  2. The taskId, taskUuid, and requestId.

  3. The SDK and JDK versions.

  4. The model, audio format, sample rate, number of channels, and bit depth.

  5. The full exception type, error code, and error message.

  6. For issues with recognition accuracy, provide the original audio file and the expected text. Do not submit a transcoded recording.