Qwen-Audio-3.0-ASR-Flash-Filetrans/Fun-ASR non-real-time speech recognition Java SDK

更新时间:
复制 MD 格式

This topic describes the parameters and API details of the Qwen-Audio-3.0-ASR-Flash-Filetrans/Fun-ASR non-real-time speech recognition Java SDK.

User guide:Non-real-time speech recognition. For input requirements such as supported audio formats, file size limits, and duration limits, see Audio specifications.

Prerequisites

  • You have activated the service and Obtain an API key. Please Configure API key as an environment variable instead of hardcoding it in your code to prevent security risks caused by code leakage.

    Note

    When you need to provide temporary access to third-party applications or users, or when you want to strictly control high-risk operations such as accessing or deleting sensitive data, we recommend using temporary authentication tokens.

    Compared with long-term API Keys, temporary authentication tokens have a short validity period (60 seconds) and higher security, making them suitable for temporary call scenarios and effectively reducing the risk of API Key leakage.

    Usage: In your code, replace the API Key originally used for authentication with the obtained temporary authentication token.

  • Install the latest DashScope SDK.

Quick start

Core class (Transcription) provides interfaces to submit a task asynchronously, wait synchronously for the task to finish, and query the task result asynchronously. You can run non-real-time speech recognition in either of the following two ways:

  • Submit a task asynchronously and wait synchronously for it to finish: after you submit a task, the current thread blocks until the task finishes and the recognition result is returned.

  • Submit a task asynchronously and query the task result asynchronously: after you submit a task, call the query interface to get the task result whenever you need it.

Submit a task asynchronously and wait synchronously for it to finish

image
  1. Configure the Request parameters.

  2. Instantiate a Core class (Transcription).

  3. Call the asyncCall method of the Core class (Transcription) to submit the task asynchronously.

    Note
    • The file transcription service processes tasks submitted through the API on a best-effort basis. After you submit a task, it enters the queued (PENDING) state. The queuing time depends on the queue length and the file duration, so it cannot be stated precisely, but it is usually within a few minutes. Once processing starts, speech recognition completes at hundreds of times real-time speed.

    • After each task finishes, the recognition result and the download URL are valid for 24 hours. After they expire, you can no longer query the task or download the result through the URL returned in a previous query.

  4. Call the wait method of the Core class (Transcription) to wait synchronously for the task to finish.

    A task can be in the PENDING, RUNNING, SUCCEEDED, or FAILED state. While the task is in the PENDING or RUNNING state, the wait interface blocks. When the task reaches the SUCCEEDED or FAILED state, the wait interface stops blocking and returns the task result.

    wait returns a Task result (TranscriptionResult).

Click to view the complete example

import com.alibaba.dashscope.audio.asr.transcription.*;
import com.alibaba.dashscope.utils.Constants;
import com.google.gson.*;

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        // The following is the configuration for the China (Beijing) region. When calling, replace "{WorkspaceId}" with your actual workspace ID. Configurations differ across regions.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
        // Create the transcription request parameters
        TranscriptionParam param =
                TranscriptionParam.builder()
                        // The API Key differs between the Singapore and Beijing regions. Get an API Key: https://help.aliyun.com/zh/model-studio/get-api-key
                        // If you have not configured the environment variable, replace the following line with your Model Studio API Key: .apiKey("sk-xxx")
                        //.apiKey("apikey")
                        .model("qwen-audio-3.0-asr-flash-filetrans") // This uses qwen-audio-3.0-asr-flash-filetrans as an example; change the model name as needed. Model list: https://help.aliyun.com/zh/model-studio/models
                        .fileUrls(
                                Arrays.asList(
                                        "{YOUR_AUDIO_URL}"))
                        .build();
        try {
            Transcription transcription = new Transcription();
            // Submit the transcription request
            TranscriptionResult result = transcription.asyncCall(param);
            System.out.println("RequestId: " + result.getRequestId());
            // Block and wait for the task to complete, then get the result
            result = transcription.wait(
                    TranscriptionQueryParam.FromTranscriptionParam(param, result.getTaskId()));
            // Print the result
            System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(result.getOutput()));
        } catch (Exception e) {
            System.out.println("error: " + e);
        }
        System.exit(0);
    }
}

Submit a task asynchronously and query the task result asynchronously

image
  1. Configure the Request parameters.

  2. Instantiate a Core class (Transcription).

  3. Call the asyncCall method of the Core class (Transcription) to submit the task asynchronously.

    Note
    • The file transcription service processes tasks submitted through the API on a best-effort basis. After you submit a task, it enters the queued (PENDING) state. The queuing time depends on the queue length and the file duration, so it cannot be stated precisely, but it is usually within a few minutes. Once processing starts, speech recognition completes at hundreds of times real-time speed.

    • After each task finishes, the recognition result and the download URL are valid for 24 hours. After they expire, you can no longer query the task or download the result through the URL returned in a previous query.

  4. Call the fetch method of the Core class (Transcription) in a loop until you get the final task result.

    When the task status is SUCCEEDED or FAILED, stop polling and process the result.

    fetch returns a Task result (TranscriptionResult).

Click to view the complete example

import com.alibaba.dashscope.audio.asr.transcription.*;
import com.alibaba.dashscope.common.TaskStatus;
import com.alibaba.dashscope.utils.Constants;
import com.google.gson.*;

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        // The following is the configuration for the China (Beijing) region. When calling, replace "{WorkspaceId}" with your actual workspace ID. Configurations differ across regions.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
        // Create the transcription request parameters
        TranscriptionParam param =
                TranscriptionParam.builder()
                        // The API Key differs between the Singapore and Beijing regions. Get an API Key: https://help.aliyun.com/zh/model-studio/get-api-key
                        // If you have not configured the environment variable, replace the following line with your Model Studio API Key: .apiKey("sk-xxx")
                        //.apiKey("apikey")
                        .model("qwen-audio-3.0-asr-flash-filetrans") // This uses qwen-audio-3.0-asr-flash-filetrans as an example; change the model name as needed. Model list: https://help.aliyun.com/zh/model-studio/models
                        .fileUrls(
                                Arrays.asList(
                                        "{YOUR_AUDIO_URL}"))
                        .build();
        try {
            Transcription transcription = new Transcription();
            // Submit the transcription request
            TranscriptionResult result = transcription.asyncCall(param);
            System.out.println("RequestId: " + result.getRequestId());
            // Poll for the task result in a loop until the task finishes
            while (true) {
                result = transcription.fetch(TranscriptionQueryParam.FromTranscriptionParam(param, result.getTaskId()));
                if (result.getTaskStatus() == TaskStatus.SUCCEEDED || result.getTaskStatus() == TaskStatus.FAILED) {
                    break;
                }
                Thread.sleep(1000);
            }
            // Print the result
            System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(result.getOutput()));
        } catch (Exception e) {
            System.out.println("error: " + e);
        }
        System.exit(0);
    }
}

Endpoints

By default, the SDK uses the endpoint of the China (Beijing) region. To switch to another region, modify Constants.baseHttpApiUrl before initialization.

China (Beijing)

https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1

When you make a call, replace {WorkspaceId} with your actual Workspace ID.

Singapore

https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1

When you make a call, replace {WorkspaceId} with your actual Workspace ID.

Important

Alibaba Cloud Model Studio has released workspace-specific domains for the China (Beijing) and Singapore regions. The new dedicated domains deliver superior performance and higher stability for inference requests. We recommend migrating to the new domains:

  • China (Beijing): from dashscope.aliyuncs.com to {WorkspaceId}.cn-beijing.maas.aliyuncs.com

  • Singapore: from dashscope-intl.aliyuncs.com to {WorkspaceId}.ap-southeast-1.maas.aliyuncs.com

Replace {WorkspaceId} with your actual Workspace ID. The existing domains remain fully functional.

Switch to the Singapore region:

import com.alibaba.dashscope.utils.Constants;

// Set this at the beginning of your code
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";

Note:

  • API keys differ across regions. Make sure you use the API key for the target region.

  • The region setting is global and affects the API calls of all DashScope SDKs.

Request parameters

Configure request parameters using the chained methods of TranscriptionParam.

Click to view the example

TranscriptionParam param = TranscriptionParam.builder()
  .model("qwen-audio-3.0-asr-flash-filetrans")
  .fileUrls(
          Arrays.asList(
                  "{YOUR_AUDIO_URL}"))
  .build();

Parameter

Type

Required

Description

model

String

Yes

The model name. Supported values include the Qwen-Audio-3.0-ASR-Flash-Filetrans and Fun-ASR model families. For details, see Supported models and regions.

fileUrls

List<String>

Yes

A list of URLs of the audio or video files to transcribe. HTTP and HTTPS are supported. A single request supports only one URL. For input requirements such as supported audio formats, file size limits, and duration limits, see Audio specifications.

If the recording is stored in Alibaba Cloud OSS, the RESTful API supports temporary URLs prefixed with oss://, whereas the SDK does not support oss://-prefixed temporary URLs.

Important
  • A temporary URL is valid for 48 hours and cannot be used after it expires. Do not use it in production.

  • The upload credential interface is rate-limited to 100 QPS and cannot be scaled up. Do not use it in production, high-concurrency, or load-testing scenarios.

  • For production, use stable storage such as Alibaba Cloud OSS to keep files available long-term and avoid rate limiting.

  • If an audio file URL set to an OSS temporary public URL is unreachable, set X-DashScope-OssResourceResolve to enable in the request header (not recommended).

    The SDK does not support configuring request headers.

vocabularyId

String

No

The ID of a precompiled hot word list.

Generate this ID in advance by calling the create hot word list API. Pass the ID during recognition to use the hot words in the list.

Suitable for scenarios where the vocabulary is known and relatively stable, and where you need to reuse the same word list across requests.

For usage details, see Precompiled hotwords.

vocabulary

Map<String, Integer>

No

Instant hot words.

Passed as key-value pairs, where the key is the hot word text (string) and the value is the hot word weight (integer). No hot word list needs to be created in advance. The weight ranges from [1, 5] or is set to 50: a value in [1, 5] makes the model more likely to output the word as the value increases; a value of 50 designates a super hot word, which greatly improves recall, but the number of super hot words cannot exceed 50.

Suitable for temporary, session-level hot word optimization.

When configured together with precompiled hot words, only the instant hot words take effect. For usage details, see Instant hotwords.

Important

Only qwen-audio-3.0-asr-flash-filetrans supports inline hotwords.

Note

Set vocabulary through the parameter method or the parameters method of the TranscriptionParam instance:

Set through parameter

Map<String, Integer> vocab = new HashMap<>();
vocab.put("John Smith", 5);
vocab.put("Jane Doe", 5);

TranscriptionParam param = TranscriptionParam.builder()
  .model("qwen-audio-3.0-asr-flash-filetrans")
  .parameter("vocabulary", vocab)
  .build();

Set through parameters

Map<String, Integer> vocab = new HashMap<>();
vocab.put("John Smith", 5);
vocab.put("Jane Doe", 5);

TranscriptionParam param = TranscriptionParam.builder()
  .model("qwen-audio-3.0-asr-flash-filetrans")
  .parameters(Collections.singletonMap("vocabulary", vocab))
  .build();

channelId

List<Integer>

No

The index of the audio tracks to recognize in a multi-track audio file. The index starts at 0. For example, [0] recognizes the first track, and [0, 1] recognizes the first and second tracks at the same time. If you omit this parameter, only the first track is processed.

Important

Each specified track is billed independently. For example, requesting [0, 1] for a single file incurs two separate charges.

Default value: [0].

specialWordFilter

String

No

The sensitive words to process during speech recognition. You can set a different handling method for each sensitive word. For details, see Sensitive word filtering.

diarizationEnabled

Boolean

No

Whether to enable speaker diarization. Disabled by default.

Applies only to mono audio. Multi-channel audio does not support speaker diarization.

When enabled, the recognition result includes a speaker_id field that distinguishes different speakers.

Note

When speaker diarization is enabled, keep the audio duration within 2 hours. Otherwise, recognition may fail or time out.

Default value: false.

For an example of speaker_id, see Recognition result description.

speakerCount

Integer

No

Important

Takes effect only when speaker diarization is enabled (diarization_enabled is set to true).

A reference value for the number of speakers. The valid range is an integer from 2 to 100 (inclusive).

By default, the number of speakers is detected automatically. If you set this value, it only guides the algorithm to output the specified count when possible and does not guarantee that exact count.

No default value.

language_hints

String[]

No

The language codes to recognize. If you can't determine the language in advance, leave it unset and the model detects the language automatically.

For Qwen-Audio-3.0-ASR-Flash-Filetrans models, you can set up to 4 values; any values beyond the first 4 are ignored. For Fun-ASR models, you can set only 1 value; if you set multiple, only the first takes effect.

Click to view the supported language codes

  • qwen-audio-3.0-asr-flash-filetrans, fun-asr, fun-asr-2025-11-07, fun-asr-mtl, fun-asr-mtl-2025-08-25:

    • zh: Chinese

    • en: English

    • ja: Japanese

    • ko: Korean

    • vi: Vietnamese

    • th: Thai

    • id: Indonesian

    • ms: Malay

    • tl: Filipino

    • hi: Hindi

    • ar: Arabic

    • fr: French

    • de: German

    • es: Spanish

    • pt: Portuguese

    • ru: Russian

    • it: Italian

    • nl: Dutch

    • sv: Swedish

    • da: Danish

    • fi: Finnish

    • no: Norwegian

    • el: Greek

    • pl: Polish

    • cs: Czech

    • hu: Hungarian

    • ro: Romanian

    • bg: Bulgarian

    • hr: Croatian

    • sk: Slovak

  • fun-asr-2025-08-25:

    • zh: Chinese

    • en: English

Note

Set language_hints through the parameter method or the parameters method of the TranscriptionParam instance:

Set through parameter

TranscriptionParam param = TranscriptionParam.builder()
  .model("qwen-audio-3.0-asr-flash-filetrans")
  .parameter("language_hints", new String[]{"zh"})
  .build();

Set through parameters

TranscriptionParam param = TranscriptionParam.builder()
  .model("qwen-audio-3.0-asr-flash-filetrans")
  .parameters(Collections.singletonMap("language_hints", new String[]{"zh"}))
  .build();

apiKey

String

No

Your API key. If you have configured the API key as an environment variable, you do not need to set it in your code. Otherwise, you must set it in your code.

Response

Task result (TranscriptionResult)

TranscriptionResult encapsulates the result of the current task.

Interface/Method

Parameter

Return value

Description

public String getRequestId()

None

requestId

Gets the requestId.

public String getTaskId()

None

taskId

Gets the taskId.

public TaskStatus getTaskStatus()

None

TaskStatus, the task status

Gets the task status.

TaskStatus is an enum. You only need to focus on the following four states: PENDING, RUNNING, SUCCEEDED, and FAILED.

Note

When a task contains multiple subtasks, the overall task status is marked as SUCCEEDED as long as any one subtask succeeds. Use the subtask_status field to check the result of each individual subtask.

public List<TranscriptionTaskResult> getResults()

None

Subtask result (TranscriptionTaskResult)

Gets the Subtask result (TranscriptionTaskResult).

Each task recognizes one or more audio files. Different audio files are processed in separate subtasks, so each task corresponds to one or more subtasks.

public JsonObject getOutput()

None

The task result, in JSON format

Gets the task result.

The result is data in JSON format. If you want to get the task result through the getOutput interface, parse it yourself after you get the result.

Click to view the JSON example

Success example

{
    "task_id":"0795ff8c-b666-4e91-bb8b-xxx",
    "task_status":"SUCCEEDED",
    "submit_time":"2025-02-13 16:12:09.109",
    "scheduled_time":"2025-02-13 16:12:09.128",
    "end_time":"2025-02-13 16:12:10.189",
    "results":[
        {
            "file_url":"{YOUR_AUDIO_URL}",
            "transcription_url":"https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/prod/paraformer-v2/20250213/16%3A12/3baafe5f-d09d-46c6-8b01-724927670edb-1.json?Expires=1739520730&OSSAccessKeyId=yourOSSAccessKeyId&Signature=BF7vPxlsJN9hkJlY%2BLReezxOwK8%3D",
            "subtask_status":"SUCCEEDED"
        }
    ],
    "task_metrics":{
        "TOTAL":1,
        "SUCCEEDED":1,
        "FAILED":0
    }
}

Error example

code” is the error code, and “message” is the error message. These two fields appear only when an error occurs. You can use them, together with the Error codes, to troubleshoot the problem.

{
          "task_id": "7bac899c-06ec-4a79-8875-xxxxxxxxxxxx",
          "task_status": "SUCCEEDED",
          "submit_time": "2024-12-16 16:30:59.170",
          "scheduled_time": "2024-12-16 16:30:59.204",
          "end_time": "2024-12-16 16:31:02.375",
          "results": [
              {
                  "file_url": "{YOUR_AUDIO_URL}",
                  "code": "InvalidFile.DownloadFailed",
                  "message": "The audio file cannot be downloaded.",
                  "subtask_status": "FAILED"
              }
          ],
          "task_metrics": {
              "TOTAL": 1,
              "SUCCEEDED": 0,
              "FAILED": 1
          }
      }

Subtask result (TranscriptionTaskResult)

TranscriptionTaskResult encapsulates the result of a subtask. A subtask recognizes a single audio file.

Interface/Method

Parameter

Return value

Description

public String getFileUrl()

None

The URL of the recognized audio file

Gets the URL of the recognized audio file.

public String getTranscriptionUrl()

None

The URL of the recognition result

Gets the URL of the recognition result. This URL is valid for 24 hours. After it expires, you can no longer query the task or download the result through the URL returned in a previous query.

The recognition result is saved as a JSON file. You can download the file through the URL or read its content directly through an HTTP request.

For the meaning of each field in the JSON data, see Recognition result description.

public TaskStatus getSubTaskStatus()

None

TaskStatus, the subtask status

Gets the subtask status.

TaskStatus is an enum. You only need to focus on the following four states: PENDING, RUNNING, SUCCEEDED, and FAILED.

public String getMessage()

None

Key information generated during task execution, which may be empty

Gets the key information generated during task execution.

When a task fails, check this content to analyze the cause.

Recognition result description

The recognition result is saved as a JSON file.

Click to view the recognition result example

{
    "file_url":"{YOUR_AUDIO_URL}",
    "properties":{
        "audio_format":"pcm_s16le",
        "channels":[
            0
        ],
        "original_sampling_rate":16000,
        "original_duration_in_milliseconds":3834
    },
    "transcripts":[
        {
            "channel_id":0,
            "content_duration_in_milliseconds":3720,
            "text":"Hello world, this is Alibaba Speech Lab.",
            "sentences":[
                {
                    "begin_time":100,
                    "end_time":3820,
                    "text":"Hello world, this is Alibaba Speech Lab.",
                    "sentence_id":1,
                    "speaker_id":0, //This field is displayed only when automatic speaker diarization is enabled
                    "words":[
                        {
                            "begin_time":100,
                            "end_time":596,
                            "text":"Hello ",
                            "punctuation":""
                        },
                        {
                            "begin_time":596,
                            "end_time":844,
                            "text":"world",
                            "punctuation":", "
                        }
                        // Other content is omitted here
                    ]
                }
            ]
        }
    ]
}

The following parameters are worth noting:

Parameter

Type

Description

audio_format

string

The audio format of the source file.

channels

array[integer]

The track index of the audio in the source file. For single-track audio, [0] is returned; for dual-track audio, [0, 1] is returned; and so on.

original_sampling_rate

integer

The sampling rate (Hz) of the audio in the source file.

original_duration_in_milliseconds

integer

The original audio duration (ms) in the source file.

channel_id

integer

The track index of the transcription result, starting from 0.

content_duration

integer

The duration (ms) of content in the track that is identified as speech.

Important

The speech recognition model service transcribes only the content in a track that is identified as speech, and meters and bills based on that duration. Non-speech content is not metered or billed. Typically, the speech content duration is shorter than the original audio duration. Because whether speech content exists is determined by an AI model, the result may differ slightly from the actual situation.

transcript

string

The paragraph-level transcription result.

sentences

array

The sentence-level transcription result.

words

array

The word-level transcription result.

begin_time

integer

The start timestamp (ms).

end_time

integer

The end timestamp (ms).

text

string

The transcription result.

speaker_id

integer

The index of the current speaker, starting from 0, used to distinguish between different speakers.

This field appears in the recognition result only when speaker diarization is enabled.

punctuation

string

The punctuation predicted after the word, if any.

Key interfaces

Task query parameter class (TranscriptionQueryParam)

TranscriptionQueryParam is used when waiting for a task to finish (calling the wait method of Transcription) or querying the task result (calling the fetch method of Transcription).

Create a TranscriptionQueryParam instance through the static method FromTranscriptionParam.

Show example

// Build the transcription request parameters
TranscriptionParam param =
        TranscriptionParam.builder()
                // If you have not set the API key as an environment variable, replace apiKey with your own API key
                //.apiKey("apikey")
                .model("qwen-audio-3.0-asr-flash-filetrans")
                .fileUrls(
                        Arrays.asList(
                                "{YOUR_AUDIO_URL}"))
                .build();
try {
    Transcription transcription = new Transcription();
    // Submit the transcription request
    TranscriptionResult result = transcription.asyncCall(param);
    System.out.println("RequestId: " + result.getRequestId());
    TranscriptionQueryParam queryParam = TranscriptionQueryParam.FromTranscriptionParam(param, result.getTaskId());
    
} catch (Exception e) {
    System.out.println("error: " + e);
}

Interface/method

Parameters

Return value

Description

public static TranscriptionQueryParam FromTranscriptionParam(TranscriptionParam param, String taskId)
  • param: a TranscriptionParam instance

  • taskId: the task ID

a TranscriptionQueryParam instance

Creates a TranscriptionQueryParam instance.

Core class (Transcription)

Import Transcription with "import com.alibaba.dashscope.audio.asr.transcription.*;". Its key interfaces are as follows:

Interface/method

Parameters

Return value

Description

public TranscriptionResult asyncCall(TranscriptionParam param)

param: the speech recognition parameters, a TranscriptionParam instance

Task result (TranscriptionResult)

Submits a speech recognition task asynchronously.

public TranscriptionResult wait(TranscriptionQueryParam queryParam)

queryParam: a TranscriptionQueryParam instance

Task result (TranscriptionResult)

Blocks the current thread until the asynchronous task ends (the task status is SUCCEEDED or FAILED).

public TranscriptionResult fetch(TranscriptionQueryParam queryParam)

queryParam: a TranscriptionQueryParam instance

Task result (TranscriptionResult)

Queries the current task result asynchronously.

Additional interfaces: batch query task status / cancel tasks

For details, see Manage asynchronous tasks. It supports batch querying non-real-time speech recognition tasks submitted within the past 24 hours, and canceling tasks in the PENDING (queued) state.

Error codes

If you encounter an error, see Error codes to troubleshoot.

When a task contains multiple subtasks, the overall task status is marked as SUCCEEDED as long as at least one subtask succeeds. Check the subtask_status field to determine the result of each subtask.

Error response example:

{
    "task_id": "7bac899c-06ec-4a79-8875-xxxxxxxxxxxx",
    "task_status": "SUCCEEDED",
    "submit_time": "2024-12-16 16:30:59.170",
    "scheduled_time": "2024-12-16 16:30:59.204",
    "end_time": "2024-12-16 16:31:02.375",
    "results": [
        {
            "file_url": "{YOUR_AUDIO_URL}",
            "code": "InvalidFile.DownloadFailed",
            "message": "The audio file cannot be downloaded.",
            "subtask_status": "FAILED"
        }
    ],
    "task_metrics": {
        "TOTAL": 1,
        "SUCCEEDED": 0,
        "FAILED": 1
    }
}

FAQ

Features

Q: Is Base64-encoded audio supported?

Base64-encoded audio is not supported. Only audio at a publicly accessible URL can be recognized. Binary streams and local files cannot be recognized directly.

Q: How do I make an audio file available at a publicly accessible URL?

The typical steps are as follows. This is one approach; the exact process varies by storage product. We recommend that you upload the audio to Alibaba Cloud OSS:

1. Choose a storage and hosting method

For example:

  • Object storage service (recommended):

    • Use a cloud provider's object storage service (such as Alibaba Cloud OSS) to upload the audio file to a bucket and set it to public access.

    • Advantages: high availability, CDN acceleration support, and easy management.

  • Web server:

    • Place the audio file on a web server that supports HTTP/HTTPS access (such as Nginx or Apache).

    • Advantages: suitable for small projects or local testing.

  • Content delivery network (CDN):

    • Host the audio file on a CDN and access it through the URL that the CDN provides.

    • Advantages: accelerates file delivery and suits high-concurrency scenarios.

2. Upload the audio file

Upload the audio according to the storage or hosting method you chose. For example:

  • Object storage service:

    • Log in to the cloud provider's console and create a bucket.

    • Upload the audio file, and set its permission to public read or generate a temporary access link.

  • Web server:

    • Place the audio file in a designated directory on the server (such as /var/www/html/audio/).

    • Make sure the file is accessible over HTTP/HTTPS.

3. Generate a publicly accessible URL

For example:

  • Object storage service:

    • After the file is uploaded, the system automatically generates a public access URL (typically in the format https://<bucket-name>.<region>.aliyuncs.com/<file-name>).

    • For a friendlier domain name, bind a custom domain and enable HTTPS.

  • Web server:

    • The access URL is usually the server address plus the file path (such as https://your-domain.com/audio/file.mp3).

  • CDN:

    • After you configure CDN acceleration, use the URL that the CDN provides (such as https://cdn.your-domain.com/audio/file.mp3).

4. Verify that the URL works

Make sure the generated URL is accessible over the public network. For example:

  • Open the URL in a browser and check whether the audio file plays.

  • Use a tool (such as curl or Postman) to verify that the URL returns the correct HTTP response (status code 200).

When using the SDK, if audio files are stored in Alibaba Cloud OSS, temporary URLs with the oss:// prefix are not supported.

When using the RESTful API, if audio files are stored in Alibaba Cloud OSS, temporary URLs with the oss:// prefix are supported:

  • The temporary URL is valid for 48 hours and cannot be used after it expires. Do not use it in a production environment.

  • The API for obtaining an upload credential is limited to 100 QPS and does not support scaling out. Do not use it in production environments, high-concurrency scenarios, or stress testing scenarios.

  • For production environments, use a stable storage service such as OSS to ensure long-term file availability and avoid rate limiting issues.

Q: How long does it take to get the recognition result?

After a task is submitted, it enters the queued (PENDING) state. The queuing time depends on the queue length and the audio duration, so it cannot be stated exactly, but it is usually within a few minutes. In general, the longer the audio, the longer it takes.

Troubleshooting

If your code returns an error, troubleshoot it based on the information in Error codes.

Q: Polling never returns a result?

This may be caused by throttling. Wait a moment and try again.

Q: Why can't the speech be recognized (no recognition result)?

Check that the audio format and sample rate are correct and meet the parameter constraints.

Use the ffprobe tool to get the audio container, codec, sample rate, channels, and other details:

ffprobe -v error -show_entries format=format_name -show_entries stream=codec_name,sample_rate,channels -of default=noprint_wrappers=1 input.xxx