Prepare audio, reuse connections, manage Java concurrency and asynchronous jobs, and handle errors in speech recognition applications.
Prepare input audio
Check the input format, sample rate, channels, and duration against the target model’s audio specifications.
- Prioritize capture quality and reduce background noise and echo. Before enabling noise suppression or AEC, compare recognition results before and after processing on the same representative, manually transcribed audio set.
- For 8 kHz telephone audio, choose a matching model and sample rate.
- Choose a model that supports the audio’s language and dialect.
- For inaccurate recognition of specialized terms, configure hotwords or context enhancement as described in Improve recognition accuracy.
Inspect and process audio
Inspect and process audio
- Inspect the audio format
- Convert the encoding and sample rate
- Trim audio
- Extract audio from video
Use FFprobe to inspect the container format, codec, sample rate, and channels:
Choose a file input method
File input methods depend on the API. For example, Qwen-Audio-ASR-Flash supports audio file URLs and Base64 Data URIs. Encode local audio as a Base64 Data URI to submit it directly. For encoding and invocation examples, see Flash HTTP API.
When submitting a file by URL, ensure the recognition service can download it while processing the task. Check permissions, URL expiration, and public network accessibility.
For production, host files in stable storage such as OSS and submit their URLs. Reuse uploaded files during batch processing to reduce repeated uploads. Before using an SDK's local file upload feature, check the upload limits of that interface. See Get a temporary file URL for the temporary file mechanism and its conditions.
Manage real-time tasks and connections
The run-task / finish-task protocol used by Qwen-Audio-ASR-Message, Qwen-Audio-ASR-Streaming, Fun-ASR-Realtime, and Paraformer supports sequential connection reuse:
- Send
run-taskwith a uniquetask_id. Wait fortask-startedbefore sending audio. - After sending the audio, send
finish-taskwith the sametask_id. - Wait for the server's
task-finishedevent to confirm completion. - Start the next task on the same connection with a new
task_id. Do not run tasks concurrently on one connection.
Handle idle and failed connections
- The connection closes automatically if no new task starts for approximately 60 seconds after task completion. Establish a new connection after an extended idle period.
- After task failure, network interruption, or a protocol error, close the old connection and create a new recognition object. Invalidate pooled objects instead of returning them as usable objects.
- Close the object pool and its connections when the application exits or stops providing recognition.
Handle extended silence during a task
If a running task needs to receive continuous silent audio, configure heartbeat=true as described by its API and continue sending silence in the required encoding. Manage idle connections after task completion as described in the preceding section. For model parameters, see the following references.
Message client events | Streaming client events | Fun-ASR client events | Paraformer client events
Configure Java concurrency
Give each running recognition task exclusive use of a Recognition object and return it only after successful completion. The following example manages recognition objects with Commons Pool 2. Create the pool once and reuse it across calls.
Add dependencies
Complete Get an API key and Install an SDK first. The complete example in this section requires DashScope Java SDK 2.18.0 or later. These dependency configurations use DashScope Java SDK 2.23.2 and Commons Pool 2.12.0:
- Maven
- Gradle
Distinguish connection, object, and request capacity
The SDK reads the following three DASHSCOPE_ environment variables. Set them before starting the process. The example in this document reads RECOGNITION_OBJECTPOOL_SIZE.
| Environment variable | Default | Purpose |
|---|---|---|
DASHSCOPE_CONNECTION_POOL_SIZE | 32 | Idle HTTP connections retained by the SDK's shared OkHttp client. |
DASHSCOPE_MAXIMUM_ASYNC_REQUESTS | 32 | Concurrent scheduling capacity for SDK asynchronous requests. Requests above this capacity wait for scheduling. |
DASHSCOPE_MAXIMUM_ASYNC_REQUESTS_PER_HOST | 32 | Asynchronous request scheduling capacity per host. |
RECOGNITION_OBJECTPOOL_SIZE | 500 | Total recognition objects allowed by this example, controlled by Commons Pool's maxTotal. |
Concurrency is the number of tasks running at the same time; RPS is the number of requests per second. Configure worker threads and object pool capacity for application concurrency, and control task start frequency according to the model’s Rate limits.
Paraformer configuration reference
Paraformer configuration reference
The following values are capacity planning references for Paraformer real-time recognition applications. Per-server concurrency means recognition tasks running at the same time. The server runs only that recognition application.
- For HTTP idle connection capacity, start from at least twice peak concurrency and adjust as needed.
- Initially set total and per-host asynchronous scheduling capacity to the same value as that connection capacity, then adjust based on observed queueing.
- For recognition object pool capacity, start from 1.5 to 2 times peak concurrency. The example default of 500 is an application setting.
| Alibaba Cloud server | Reference task concurrency | Recognition pool capacity | HTTP idle connection capacity |
|---|---|---|---|
| 4 vCPUs, 8 GiB | 100 | 500 | 2000 |
| 8 vCPUs, 16 GiB | 200 | 500 | 2000 |
| 16 vCPUs, 32 GiB | 400 | 500 | 2000 |
These settings apply to a server dedicated to the Paraformer real-time recognition application. Adjust capacity for audio transmission rate, client resources, and application workload. For model API limits, see Rate limits.
Implement a recognition object pool
Use the complete lifecycle below. When maxTotal is reached and no idle object is available, this example’s borrowObject waits for an object to be returned. Objects are created on demand, and WebSocket connections are established when recognition requests start.
- Borrow a
Recognitionobject, start recognition, and send audio. - Send the end command and wait for completion. For asynchronous calls, also check the error callback.
- After success, call
returnObjectso subsequent tasks can reuse the object. - On failure or interruption, call
invalidateObject. The factory'sdestroyObjectcloses the connection. - After all tasks finish, close the pool to release connections held by idle objects.
RecognitionPoolExample.java. Prepare asr-example.pcm containing 16 kHz, 16-bit, mono PCM audio, set DASHSCOPE_API_KEY, and replace the workspace and endpoint with the configuration for the target region (see Endpoints). The example uses three worker threads to process nine recognition tasks.
Warm up and measure latency
Warm up by sending actual recognition requests to establish WebSocket connections that subsequent tasks can reuse.
- Send requests at the intended production concurrency before collecting measurements. One to two minutes is a starting reference; adjust it to the workload.
- Confirm that reusable connections exist before collecting steady-state latency. Report cold-start and steady-state data separately.
- Connections can close during application idle periods, requiring setup on a later call. Warm up again as needed before new performance measurements.
Manage asynchronous transcription jobs
For high-concurrency batch transcription, prefer task completion callbacks to reduce polling requests. For callback configuration, message structure, and result retrieval, see Configure asynchronous task callbacks.
Control submission, query, and upload rates
- Task submission: Control submission frequency according to the target model’s Rate limits.
- Status queries: The query API has a default limit of 20 QPS, which can be increased to 100 QPS (contact your Alibaba Cloud account manager to request an increase), per Alibaba Cloud primary account, including its RAM users. When polling, start with an interval of 2 to 5 seconds and adjust it to the number of tasks so that the total query rate remains within the limit. For queries, batch queries, and task cancellation, see Manage asynchronous tasks.
- Temporary file uploads: The file upload credential API is limited to 100 QPS per Alibaba Cloud primary account and model. This limit cannot be increased. Use stable storage such as OSS for production and high-concurrency workloads. For temporary upload procedures and limits, see Get a temporary file URL.
Save recognition results promptly
Download and save result files promptly after task success. For example, transcription_url in Qwen-Audio-ASR-Filetrans HTTP API is valid for 24 hours. Download and persist the results before it expires.
- When a response contains a
resultsarray, check eachsubtask_statusbefore downloading transcription JSON for successful files. Save the timestamps, speaker information, and other fields needed by the application. - Retain the task-to-file mapping and final status. If a download fails, keep the task record and retry within the URL validity period.
Handle errors and retries
Decide whether to retry based on the error type. Record the request ID, task ID, model, region, and failure stage to distinguish input and permission issues from temporary service failures.
| Issue | Action |
|---|---|
| Input file or parameter errors | Check the URL, encoding, sample rate, channels, and parameter ranges. Correct the issue before submitting again. |
| Authentication or endpoint configuration errors | Check the API key, workspace, and endpoint region, then correct the configuration according to the error message. |
| Rate limiting | Reduce request frequency or task start rate and follow Rate limits. Avoid immediate retry loops. |
| Network timeouts, interruptions, or temporary server errors (5xx) | For failed queries or downloads, use backoff retries with limits on attempts and total wait time. After an asynchronous submission timeout, query the task if a task_id was received. If no task_id was received, decide whether to resubmit based on the application’s tolerance for duplicate processing and charges. |
| Asynchronous task or file processing failures | Retain task-level and file-level errors, identify the cause, then decide whether to correct the input or resubmit. |
Related documentation
- Basic integration: Real-time speech recognition and Non-real-time speech recognition.
- Recognition quality: Improve recognition accuracy.
- Asynchronous jobs: Configure asynchronous task callbacks and Manage asynchronous tasks.