Os modelos de reconhecimento de fala não em tempo real convertem áudio gravado em texto. Eles oferecem suporte a reconhecimento multilíngue, reconhecimento de canto, rejeição de ruído e diarização de falantes, o que os torna adequados para transcrição de reuniões, análise de chamadas, geração de legendas e cenários semelhantes.
Visão geral
Transcreva arquivos de áudio e vídeo gravados em lotes por meio de tarefas assíncronas.
- O aprimoramento de contexto melhora a precisão do reconhecimento por meio de um contexto configurável.
- Palavras-chave personalizadas aumentam a precisão no reconhecimento de nomes próprios usando uma lista de palavras predefinida.
- Os recursos configuráveis incluem diarização de falantes, filtragem de palavras sensíveis e carimbos de data/hora no nível da frase ou da palavra.
- A transcrição assíncrona aceita um único arquivo de áudio com duração de até 12 horas e tamanho máximo de 2 GB.
- Há suporte para qualquer taxa de amostragem, além de formatos de áudio e vídeo populares como AAC, WAV e MP3.
Para cenários em tempo real, como legendas ao vivo, reuniões online e assistentes de voz, use Real-time speech recognition. Para obter orientações sobre a escolha do modelo, consulte Speech-to-text.
Pré-requisitos
- Uma chave de API foi Obtain an API key e configured as an environment variable.
- Para chamar a API por meio do DashScope SDK, install the latest SDK.
Início rápido
ImportanteNo reconhecimento de fala não em tempo real, os modelos Qwen-Audio-3.0-ASR-Flash-Filetrans, Fun-ASR, Qwen3-ASR-Flash-Filetrans e Paraformer utilizam chamadas assíncronas. Defina o cabeçalho da requisição X-DashScope-Async: enable, envie a tarefa e, em seguida, faça polling na API de consulta para recuperar o resultado. Outros modelos, como Fun-ASR-Flash e Qwen3-ASR-Flash, utilizam chamadas síncronas.
Se você chamar uma implantação dedicada do service de modelo e receber o erro current user api does not support asynchronous calls, significa que a implantação suporta apenas chamadas síncronas. Altere o cabeçalho da requisição para X-DashScope-Async: disable e mantenha o restante da chamada inalterado.
Qwen-Audio-3.0-ASR-Flash-Filetrans/Fun-ASR
Como os arquivos de áudio e vídeo podem ser grandes, a API de transcrição de arquivos utiliza chamadas assíncronas: envie uma tarefa, faça polling na API de consulta para verificar seu status e recupere o resultado do reconhecimento após a conclusão da tarefa.
cURL
Ao chamar a API com cURL, primeiro envie a tarefa para obter um task_id e, em seguida, consulte o resultado da tarefa usando esse ID.
Enviar uma tarefa
A configuração a seguir destina-se à região Singapore. Substitua {WorkspaceId} pelo seu Workspace ID real. A configuração varia conforme a região.
curl -X POST 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/audio/asr/transcription' \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-Async: enable" \
-d '{
"model": "qwen-audio-3.0-asr-flash-filetrans",
"input": {
"file_urls": [
"{YOUR_AUDIO_URL}"
]
},
"parameters": {
"channel_id": [0],
"language_hints": ["zh", "en"]
}
}'
Obter o resultado da tarefa
Esta API de consulta permite 20 QPS por padrão e pode escalar até 100 QPS. Para uma frequência maior ou para evitar limitações causadas pelo polling, configure um callback de tarefa assíncrona (consulte High-concurrency scenarios: use callbacks instead of polling).
A configuração a seguir destina-se à região Singapore. Substitua {WorkspaceId} pelo seu Workspace ID real. A configuração varia conforme a região.
curl -X GET 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}' \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json"
Baixar o resultado do reconhecimento
Após o sucesso da tarefa, o campo output.results[].transcription_url retornado pela API de consulta aponta para um arquivo JSON publicamente baixável que contém o resultado completo do reconhecimento. Essa URL é válida por 24 horas por padrão; portanto, baixe e salve o arquivo prontamente.
# Replace {transcription_url} with the transcription_url value returned by the query API
curl -sS '{transcription_url}' -o transcription.json
cat transcription.json | jq .
Python
from http import HTTPStatus
from dashscope.audio.asr import Transcription
from urllib import request
import dashscope
import os
import json
# The following is the configuration for the Singapore region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# The API Key differs between the Singapore and Beijing regions. Get an API Key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# If you have not configured the environment variable, replace the following line with your Alibaba Cloud Model Studio API Key: dashscope.api_key = "sk-xxx"
dashscope.api_key = os.getenv("DASHSCOPE_API_KEY")
task_response = Transcription.async_call(
model='qwen-audio-3.0-asr-flash-filetrans',
file_urls=['{YOUR_AUDIO_URL}'],
language_hints=['zh', 'en'] # language_hints is an optional parameter used to specify the language codes of the audio to be recognized. For the value range, see the API reference documentation.
)
transcription_response = Transcription.wait(task=task_response.output.task_id)
if transcription_response.status_code == HTTPStatus.OK:
for transcription in transcription_response.output['results']:
if transcription['subtask_status'] == 'SUCCEEDED':
url = transcription['transcription_url']
result = json.loads(request.urlopen(url).read().decode('utf8'))
print(json.dumps(result, indent=4,
ensure_ascii=False))
else:
print('transcription failed!')
print(transcription)
else:
print('Error: ', transcription_response.output.message)
Java
import com.alibaba.dashscope.audio.asr.transcription.*;
import com.alibaba.dashscope.utils.Constants;
import com.google.gson.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
// The following is the configuration for the Singapore region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.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://www.alibabacloud.com/help/zh/model-studio/get-api-key
// If you have not configured the environment variable, replace the following line with your Alibaba Cloud Model Studio API Key: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen-audio-3.0-asr-flash-filetrans")
// language_hints is an optional parameter used to specify the language codes of the audio to be recognized. For the value range, see the API reference documentation.
.parameter("language_hints", new String[]{"zh", "en"})
.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());
// Check whether the task was submitted successfully
if (result.getTaskId() == null) {
System.out.println("Error: " + result.getOutput());
System.exit(1);
}
// Block and wait for the task to complete and get the result
result = transcription.wait(
TranscriptionQueryParam.FromTranscriptionParam(param, result.getTaskId()));
// Get the transcription result
List<TranscriptionTaskResult> taskResultList = result.getResults();
if (taskResultList != null && taskResultList.size() > 0) {
for (TranscriptionTaskResult taskResult : taskResultList) {
String transcriptionUrl = taskResult.getTranscriptionUrl();
HttpURLConnection connection =
(HttpURLConnection) new URL(transcriptionUrl).openConnection();
connection.setRequestMethod("GET");
connection.connect();
BufferedReader reader =
new BufferedReader(new InputStreamReader(connection.getInputStream()));
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement jsonResult = gson.fromJson(reader, JsonObject.class);
System.out.println(gson.toJson(jsonResult));
}
}
} catch (Exception e) {
System.out.println("error: " + e);
}
System.exit(0);
}
}
O resultado completo do reconhecimento é impresso no console em formato JSON. Ele contém o texto transcrito juntamente com os tempos de início e fim de cada segmento no arquivo de áudio ou vídeo, em milissegundos.
- Resultado do reconhecimento
{
"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": 2480,
"text": "Hello World, this is the Alibaba Speech Lab.",
"sentences": [
{
"begin_time": 760,
"end_time": 3240,
"text": "Hello World, this is the Alibaba Speech Lab.",
"sentence_id": 1,
"words": [
{
"begin_time": 760,
"end_time": 1000,
"text": "Hello",
"punctuation": ""
},
{
"begin_time": 1000,
"end_time": 1120,
"text": " World",
"punctuation": ","
},
{
"begin_time": 1400,
"end_time": 1920,
"text": "this is",
"punctuation": ""
},
{
"begin_time": 1920,
"end_time": 2520,
"text": "the Alibaba",
"punctuation": ""
},
{
"begin_time": 2520,
"end_time": 2840,
"text": "Speech",
"punctuation": ""
},
{
"begin_time": 2840,
"end_time": 3240,
"text": "Lab",
"punctuation": "."
}
]
}
]
}
]
}
Qwen-Audio-3.0-ASR-Flash/Fun-ASR-Flash
As séries de modelos Qwen-Audio-3.0-ASR-Flash e Fun-ASR-Flash suportam chamadas síncronas para arquivos de áudio com menos de 5 minutos e podem retornar resultados de reconhecimento em modo streaming ou não streaming.
A configuração a seguir destina-se à região Singapore. Substitua {WorkspaceId} pelo seu Workspace ID real. A configuração varia conforme a região. A chave de API para a região Singapore difere daquela usada na região Beijing.
curl --location --request POST 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--header "X-DashScope-SSE: disable" \
--data '{
"model": "qwen-audio-3.0-asr-flash",
"input": {
"messages": [
{
"role": "user",
"content": [
{
"type": "input_audio",
"input_audio": {
"data": "{YOUR_AUDIO_URL}"
}
}
]
}
]
},
"parameters": {
"format": "wav",
"sample_rate": "16000"
}
}'
ImportanteNota: A estrutura de resposta retornada pelas séries de modelos Qwen-Audio-3.0-ASR-Flash e Fun-ASR-Flash por meio da API síncrona do DashScope (o endpoint multimodal-generation) difere do formato de resposta multimodal padrão do DashScope. A estrutura real da resposta é a seguinte:
{
"output": {
"output": {
"sentence": {
"text": "Recognized text content"
}
},
"text": "Hello World, this is the Alibaba Speech Lab."
},
"request_id": "..."
}
Neste caso, output.output.sentence.text e o campo de nível superior output.text correspondem aos campos de texto reconhecido, e não há campo choices. Faça o parsing da resposta adequadamente.
Qwen3-ASR-Flash-Filetrans
O modelo Qwen3-ASR-Flash-Filetrans foi projetado para transcrição assíncrona de arquivos de áudio e suporta gravações de até 12 horas. Ele aceita apenas URLs públicas de arquivos de áudio e não oferece suporte a upload de arquivos locais. Quando a tarefa é concluída, ele retorna todo o resultado do reconhecimento de uma só vez.
cURL
Ao chamar a API com cURL, primeiro envie a tarefa para obter um task_id e, em seguida, consulte o resultado da tarefa usando esse ID.
Enviar uma tarefa
A configuração a seguir destina-se à região Singapore. Substitua {WorkspaceId} pelo seu Workspace ID real. A configuração varia conforme a região.
curl -X POST 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/audio/asr/transcription' \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-Async: enable" \
-d '{
"model": "qwen3-asr-flash-filetrans",
"input": {
"file_url": "{YOUR_AUDIO_URL}"
},
"parameters": {
"channel_id":[
0
],
"enable_itn": false,
"enable_words": true
}
}'
Obter o resultado da tarefa
Esta API de consulta permite 20 QPS por padrão e pode escalar até 100 QPS. Para uma frequência maior ou para evitar limitações causadas pelo polling, configure um callback de tarefa assíncrona (consulte High-concurrency scenarios: use callbacks instead of polling).
A configuração a seguir destina-se à região Singapore. Substitua {WorkspaceId} pelo seu Workspace ID real. A configuração varia conforme a região.
curl -X GET 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}' \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json"
Baixar o resultado do reconhecimento
Após o sucesso da tarefa, o campo output.result.transcription_url retornado pela API de consulta aponta para um arquivo JSON publicamente baixável que contém o resultado completo do reconhecimento. Essa URL é válida por 24 horas por padrão; portanto, baixe e salve o arquivo prontamente.
# Replace {transcription_url} with the transcription_url value returned by the query API
curl -sS '{transcription_url}' -o transcription.json
cat transcription.json | jq .
Exemplo completo
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import okhttp3.*;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class Main {
// The following is the configuration for the Singapore region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
private static final String API_URL_SUBMIT = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/audio/asr/transcription";
// The following is the configuration for the Singapore region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
private static final String API_URL_QUERY = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/";
private static final Gson gson = new Gson();
public static void main(String[] args) {
// The API Key differs between the Singapore and Beijing regions. Get an API Key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// If you have not configured the environment variable, replace the following line with your Alibaba Cloud Model Studio API Key: String apiKey = "sk-xxx"
String apiKey = System.getenv("DASHSCOPE_API_KEY");
OkHttpClient client = new OkHttpClient();
// 1. Submit the task
/*String payloadJson = """
{
"model": "qwen3-asr-flash-filetrans",
"input": {
"file_url": "{YOUR_AUDIO_URL}"
},
"parameters": {
"channel_id": [0],
"enable_itn": false,
"language": "zh"
}
}
""";*/
String payloadJson = """
{
"model": "qwen3-asr-flash-filetrans",
"input": {
"file_url": "{YOUR_AUDIO_URL}"
},
"parameters": {
"channel_id": [0],
"enable_itn": false,
"enable_words": true
}
}
""";
RequestBody body = RequestBody.create(payloadJson, MediaType.get("application/json; charset=utf-8"));
Request submitRequest = new Request.Builder()
.url(API_URL_SUBMIT)
.addHeader("Authorization", "Bearer " + apiKey)
.addHeader("Content-Type", "application/json")
.addHeader("X-DashScope-Async", "enable")
.post(body)
.build();
String taskId = null;
try (Response response = client.newCall(submitRequest).execute()) {
if (response.isSuccessful() && response.body() != null) {
String respBody = response.body().string();
ApiResponse apiResp = gson.fromJson(respBody, ApiResponse.class);
if (apiResp.output != null) {
taskId = apiResp.output.taskId;
System.out.println("Task submitted, task_id: " + taskId);
} else {
System.out.println("Submission response content: " + respBody);
return;
}
} else {
System.out.println("Task submission failed! HTTP code: " + response.code());
if (response.body() != null) {
System.out.println(response.body().string());
}
return;
}
} catch (IOException e) {
e.printStackTrace();
return;
}
// 2. Poll the task status
boolean finished = false;
while (!finished) {
try {
TimeUnit.SECONDS.sleep(2); // Wait 2 seconds before querying again
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
String queryUrl = API_URL_QUERY + taskId;
Request queryRequest = new Request.Builder()
.url(queryUrl)
.addHeader("Authorization", "Bearer " + apiKey)
.addHeader("X-DashScope-Async", "enable")
.addHeader("Content-Type", "application/json")
.get()
.build();
try (Response response = client.newCall(queryRequest).execute()) {
if (response.body() != null) {
String queryResponse = response.body().string();
ApiResponse apiResp = gson.fromJson(queryResponse, ApiResponse.class);
if (apiResp.output != null && apiResp.output.taskStatus != null) {
String status = apiResp.output.taskStatus;
System.out.println("Current task status: " + status);
if ("SUCCEEDED".equalsIgnoreCase(status)
|| "FAILED".equalsIgnoreCase(status)
|| "UNKNOWN".equalsIgnoreCase(status)) {
finished = true;
System.out.println("Task completed, final result: ");
System.out.println(queryResponse);
}
} else {
System.out.println("Query response content: " + queryResponse);
}
}
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
static class ApiResponse {
@SerializedName("request_id")
String requestId;
Output output;
}
static class Output {
@SerializedName("task_id")
String taskId;
@SerializedName("task_status")
String taskStatus;
}
}
import os
import time
import requests
import json
# The following is the configuration for the Singapore region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
API_URL_SUBMIT = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/audio/asr/transcription"
# The following is the configuration for the Singapore region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
API_URL_QUERY_BASE = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/"
def main():
# The API Key differs between the Singapore and Beijing regions. Get an API Key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# If you have not configured the environment variable, replace the following line with your Alibaba Cloud Model Studio API Key: api_key = "sk-xxx"
api_key = os.getenv("DASHSCOPE_API_KEY")
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"X-DashScope-Async": "enable"
}
# 1. Submit the task
payload = {
"model": "qwen3-asr-flash-filetrans",
"input": {
"file_url": "{YOUR_AUDIO_URL}"
},
"parameters": {
"channel_id": [0],
# "language": "zh",
"enable_itn": False,
"enable_words": True
}
}
print("Submitting ASR transcription task...")
try:
submit_resp = requests.post(API_URL_SUBMIT, headers=headers, data=json.dumps(payload))
except requests.RequestException as e:
print(f"Failed to request task submission: {e}")
return
if submit_resp.status_code != 200:
print(f"Task submission failed! HTTP code: {submit_resp.status_code}")
print(submit_resp.text)
return
resp_data = submit_resp.json()
output = resp_data.get("output")
if not output or "task_id" not in output:
print("Abnormal submission response content:", resp_data)
return
task_id = output["task_id"]
print(f"Task submitted, task_id: {task_id}")
# 2. Poll the task status
finished = False
while not finished:
time.sleep(2) # Wait 2 seconds before querying again
query_url = API_URL_QUERY_BASE + task_id
try:
query_resp = requests.get(query_url, headers=headers)
except requests.RequestException as e:
print(f"Failed to request task query: {e}")
return
if query_resp.status_code != 200:
print(f"Task query failed! HTTP code: {query_resp.status_code}")
print(query_resp.text)
return
query_data = query_resp.json()
output = query_data.get("output")
if output and "task_status" in output:
status = output["task_status"]
print(f"Current task status: {status}")
if status.upper() in ("SUCCEEDED", "FAILED", "UNKNOWN"):
finished = True
print("Task completed. The final result is as follows:")
print(json.dumps(query_data, indent=2, ensure_ascii=False))
else:
print("Query response content:", query_data)
if __name__ == "__main__":
main()
Java SDK
import com.alibaba.dashscope.audio.qwen_asr.*;
import com.alibaba.dashscope.utils.Constants;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// The following is the configuration for the Singapore region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
QwenTranscriptionParam param =
QwenTranscriptionParam.builder()
// The API Key differs between the Singapore and Beijing regions. Get an API Key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// If you have not configured the environment variable, replace the following line with your Alibaba Cloud Model Studio API Key: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen3-asr-flash-filetrans")
.fileUrl("{YOUR_AUDIO_URL}")
//.parameter("language", "zh")
//.parameter("channel_id", new ArrayList<String>(){{add("0");add("1");}})
.parameter("enable_itn", false)
.parameter("enable_words", true)
.build();
try {
QwenTranscription transcription = new QwenTranscription();
// Submit the task
QwenTranscriptionResult result = transcription.asyncCall(param);
System.out.println("create task result: " + result);
// Check whether the task was submitted successfully
if (result.getTaskId() == null) {
System.out.println("Error: " + result.getOutput());
return;
}
// Query the task status
result = transcription.fetch(QwenTranscriptionQueryParam.FromTranscriptionParam(param, result.getTaskId()));
System.out.println("task status: " + result);
// Wait for the task to complete
result =
transcription.wait(
QwenTranscriptionQueryParam.FromTranscriptionParam(param, result.getTaskId()));
System.out.println("task result: " + result);
// Get the speech recognition result
QwenTranscriptionTaskResult taskResult = result.getResult();
if (taskResult != null) {
// Get the URL of the recognition result
String transcriptionUrl = taskResult.getTranscriptionUrl();
// Get the result corresponding to the URL
HttpURLConnection connection =
(HttpURLConnection) new URL(transcriptionUrl).openConnection();
connection.setRequestMethod("GET");
connection.connect();
BufferedReader reader =
new BufferedReader(new InputStreamReader(connection.getInputStream()));
// Format and output the json result
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(gson.fromJson(reader, JsonObject.class)));
}
} catch (Exception e) {
System.out.println("error: " + e);
}
}
}
Python SDK
import json
import os
import sys
from http import HTTPStatus
import dashscope
from dashscope.audio.qwen_asr import QwenTranscription
from dashscope.api_entities.dashscope_response import TranscriptionResponse
# run the transcription script
if __name__ == '__main__':
# The API Key differs between the Singapore and Beijing regions. Get an API Key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# If you have not configured the environment variable, replace the following line with your Alibaba Cloud Model Studio API Key: dashscope.api_key = "sk-xxx"
dashscope.api_key = os.getenv("DASHSCOPE_API_KEY")
# The following is the configuration for the Singapore region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
task_response = QwenTranscription.async_call(
model='qwen3-asr-flash-filetrans',
file_url='{YOUR_AUDIO_URL}',
#language="",
enable_itn=False,
enable_words=True
)
print(f'task_response: {task_response}')
print(task_response.output.task_id)
query_response = QwenTranscription.fetch(task=task_response.output.task_id)
print(f'query_response: {query_response}')
task_result = QwenTranscription.wait(task=task_response.output.task_id)
print(f'task_result: {task_result}')
Qwen3-ASR-Flash
O Qwen3-ASR-Flash suporta gravações de até 5 minutos, aceita uma URL pública de arquivo de áudio ou upload de arquivo local como entrada e retorna resultados de reconhecimento em modo streaming.
Entrada: URL do arquivo de áudio
Python SDK
import os
import dashscope
# The following is the configuration for the Singapore region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
{"role": "user", "content": [{"audio": "{YOUR_AUDIO_URL}"}]}
]
response = dashscope.MultiModalConversation.call(
# The API Key differs between the Singapore/US regions and the Beijing region. Get an API Key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# If you have not configured the environment variable, replace the following line with your Alibaba Cloud Model Studio API Key: api_key = "sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
# If you use a model in the US region, add the "-us" suffix after the model name, for example, qwen3-asr-flash-us
model="qwen3-asr-flash",
messages=messages,
result_format="message",
asr_options={
#"language": "zh", # Optional. If you know the language of the audio, you can use this parameter to specify the language to recognize, to improve recognition accuracy
"enable_itn":False
}
)
print(response)
Java SDK
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
public class Main {
public static void simpleMultiModalConversationCall()
throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage userMessage = MultiModalMessage.builder()
.role(Role.USER.getValue())
.content(Arrays.asList(
Collections.singletonMap("audio", "{YOUR_AUDIO_URL}")))
.build();
Map<String, Object> asrOptions = new HashMap<>();
asrOptions.put("enable_itn", false);
// asrOptions.put("language", "zh"); // Optional. If you know the language of the audio, you can use this parameter to specify the language to recognize, to improve recognition accuracy
MultiModalConversationParam param = MultiModalConversationParam.builder()
// The API Key differs between the Singapore/US regions and the Beijing region. Get an API Key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// If you have not configured the environment variable, replace the following line with your Alibaba Cloud Model Studio API Key: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// If you use a model in the US region, add the "-us" suffix after the model name, for example, qwen3-asr-flash-us
.model("qwen3-asr-flash")
.message(userMessage)
.parameter("asr_options", asrOptions)
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
// The following is the configuration for the Singapore region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
simpleMultiModalConversationCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
cURL
A configuração abaixo refere-se à região Singapore. Substitua {WorkspaceId} pelo seu Workspace ID real. A configuração varia conforme a região.
curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3-asr-flash",
"input": {
"messages": [
{
"content": [
{
"audio": "{YOUR_AUDIO_URL}"
}
],
"role": "user"
}
]
},
"parameters": {
"asr_options": {
"enable_itn": false
}
}
}'
Entrada: Arquivo de áudio codificado em Base64
É possível passar dados codificados em Base64 (Data URL) no formato data:<mediatype>;base64,<data>.
-
<mediatype>: o tipo MIME.Varia conforme o formato do áudio, por exemplo:
- WAV:
audio/wav - MP3:
audio/mpeg
- WAV:
-
<data>: a string do áudio codificada em Base64.A codificação Base64 aumenta o tamanho do arquivo, portanto mantenha o arquivo original pequeno o suficiente para que o resultado codificado ainda respeite o limite de tamanho de áudio de entrada (10 MB).
-
Exemplo:
data:audio/wav;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA//PAxABQ/BXRbMPe4IQAhl9Clique para visualizar o código de exemplo
import base64, pathlib # input.mp3 is the local audio file used for voice cloning. Replace it with the path to your own audio file and make sure it meets the audio requirements. file_path = pathlib.Path("{YOUR_AUDIO_FILE}") base64_str = base64.b64encode(file_path.read_bytes()).decode() data_uri = f"data:audio/mpeg;base64,{base64_str}"import java.nio.file.*; import java.util.Base64; public class Main { /** * filePath is the local audio file used for voice cloning. Replace it with the path to your own audio file and make sure it meets the audio requirements. */ public static String toDataUrl(String filePath) throws Exception { byte[] bytes = Files.readAllBytes(Paths.get(filePath)); String encoded = Base64.getEncoder().encodeToString(bytes); return "data:audio/mpeg;base64," + encoded; } // Usage example public static void main(String[] args) throws Exception { System.out.println(toDataUrl("{YOUR_AUDIO_FILE}")); } }
import base64
import dashscope
import os
import pathlib
# The following is the configuration for the Singapore region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# Replace with the actual audio file path
file_path = "{YOUR_AUDIO_FILE}"
# Replace with the actual MIME type of the audio file
audio_mime_type = "audio/mpeg"
file_path_obj = pathlib.Path(file_path)
if not file_path_obj.exists():
raise FileNotFoundError(f"Audio file does not exist: {file_path}")
base64_str = base64.b64encode(file_path_obj.read_bytes()).decode()
data_uri = f"data:{audio_mime_type};base64,{base64_str}"
messages = [
{"role": "user", "content": [{"audio": data_uri}]}
]
response = dashscope.MultiModalConversation.call(
# The API Key differs between the Singapore/US regions and the Beijing region. Get an API Key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# If you have not configured the environment variable, replace the following line with your Alibaba Cloud Model Studio API Key: api_key = "sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# If you use a model in the US region, add the "-us" suffix after the model name, for example, qwen3-asr-flash-us
model="qwen3-asr-flash",
messages=messages,
result_format="message",
asr_options={
# "language": "zh", # Optional. If you know the language of the audio, you can use this parameter to specify the language to recognize, to improve recognition accuracy
"enable_itn":False
}
)
print(response)
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
public class Main {
// Replace with the actual audio file path
private static final String AUDIO_FILE = "{YOUR_AUDIO_FILE}";
// Replace with the actual MIME type of the audio file
private static final String AUDIO_MIME_TYPE = "audio/mpeg";
public static void simpleMultiModalConversationCall()
throws ApiException, NoApiKeyException, UploadFileException, IOException {
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage userMessage = MultiModalMessage.builder()
.role(Role.USER.getValue())
.content(Arrays.asList(
Collections.singletonMap("audio", toDataUrl())))
.build();
Map<String, Object> asrOptions = new HashMap<>();
asrOptions.put("enable_itn", false);
// asrOptions.put("language", "zh"); // Optional. If you know the language of the audio, you can use this parameter to specify the language to recognize, to improve recognition accuracy
MultiModalConversationParam param = MultiModalConversationParam.builder()
// The API Key differs between the Singapore/US regions and the Beijing region. Get an API Key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// If you have not configured the environment variable, replace the following line with your Alibaba Cloud Model Studio API Key: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// If you use a model in the US region, add the "-us" suffix after the model name, for example, qwen3-asr-flash-us
.model("qwen3-asr-flash")
.message(userMessage)
.parameter("asr_options", asrOptions)
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
// The following is the configuration for the Singapore region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
simpleMultiModalConversationCall();
} catch (ApiException | NoApiKeyException | UploadFileException | IOException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
// Generate the data URI
public static String toDataUrl() throws IOException {
byte[] bytes = Files.readAllBytes(Paths.get(AUDIO_FILE));
String encoded = Base64.getEncoder().encodeToString(bytes);
return "data:" + AUDIO_MIME_TYPE + ";base64," + encoded;
}
}
Entrada: caminho absoluto de um arquivo de áudio local
Ao processar um arquivo de áudio local com o DashScope SDK, informe o caminho do arquivo. Consulte a tabela a seguir para montar o caminho correto conforme seu método de chamada e sistema operacional.
Sistema | SDK | Caminho do arquivo a ser informado | Exemplo |
|---|---|---|---|
Linux ou macOS | Python SDK | file://{caminho absoluto do arquivo} | file:///home/images/test.png |
Java SDK | |||
Windows | Python SDK | file://{caminho absoluto do arquivo} | file://D:/images/test.png |
Java SDK | file:///{caminho absoluto do arquivo} | file:///D:/images/test.png |
ImportanteChamadas com arquivos locais têm limite de 100 QPS e não permitem aumento de escala, portanto não são adequadas para ambientes de produção, alta concorrência ou testes de estresse. Para maior concorrência, faça upload do arquivo no OSS e utilize uma URL na chamada.
import os
import dashscope
# The following is the configuration for the Singapore region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# Replace ABSOLUTE_PATH/{YOUR_AUDIO_FILE} with the absolute path of your local audio file
audio_file_path = "file://ABSOLUTE_PATH/{YOUR_AUDIO_FILE}"
messages = [
{"role": "user", "content": [{"audio": audio_file_path}]}
]
response = dashscope.MultiModalConversation.call(
# The API Key differs between the Singapore/US regions and the Beijing region. Get an API Key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# If you have not configured the environment variable, replace the following line with your Alibaba Cloud Model Studio API Key: api_key = "sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
# If you use a model in the US region, add the "-us" suffix after the model name, for example, qwen3-asr-flash-us
model="qwen3-asr-flash",
messages=messages,
result_format="message",
asr_options={
# "language": "zh", # Optional. If you know the language of the audio, you can use this parameter to specify the language to recognize, to improve recognition accuracy
"enable_itn":False
}
)
print(response)
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
public class Main {
public static void simpleMultiModalConversationCall()
throws ApiException, NoApiKeyException, UploadFileException {
// Replace ABSOLUTE_PATH/{YOUR_AUDIO_FILE} with the absolute path of your local file
String localFilePath = "file://ABSOLUTE_PATH/{YOUR_AUDIO_FILE}";
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage userMessage = MultiModalMessage.builder()
.role(Role.USER.getValue())
.content(Arrays.asList(
Collections.singletonMap("audio", localFilePath)))
.build();
Map<String, Object> asrOptions = new HashMap<>();
asrOptions.put("enable_itn", false);
// asrOptions.put("language", "zh"); // Optional. If you know the language of the audio, you can use this parameter to specify the language to recognize, to improve recognition accuracy
MultiModalConversationParam param = MultiModalConversationParam.builder()
// The API Key differs between the Singapore and Beijing regions. Get an API Key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// If you have not configured the environment variable, replace the following line with your Alibaba Cloud Model Studio API Key: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// If you use a model in the US region, add the "-us" suffix after the model name, for example, qwen3-asr-flash-us
.model("qwen3-asr-flash")
.message(userMessage)
.parameter("asr_options", asrOptions)
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
// The following is the configuration for the Singapore region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
simpleMultiModalConversationCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
Saída em streaming
O modelo gera resultados intermediários passo a passo, e o resultado final é montado a partir deles. Uma chamada sem streaming aguarda a geração de todos os resultados e os retorna de uma só vez, enquanto uma chamada com streaming retorna os resultados à medida que são gerados, reduzindo significativamente o tempo até o primeiro token. Escolha o parâmetro de streaming correspondente ao seu método de chamada:
- DashScope Python SDK: defina o parâmetro
streamcomo true. - DashScope Java SDK: chame a API
streamCall. - DashScope HTTP: defina o cabeçalho
X-DashScope-SSEcomoenable.
Python SDK
import os
import dashscope
# The following is the configuration for the Singapore region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
{"role": "user", "content": [{"audio": "{YOUR_AUDIO_URL}"}]}
]
response = dashscope.MultiModalConversation.call(
# The API Key differs between the Singapore/US regions and the Beijing region. Get an API Key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# If you have not configured the environment variable, replace the following line with your Alibaba Cloud Model Studio API Key: api_key = "sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
# If you use a model in the US region, add the "-us" suffix after the model name, for example, qwen3-asr-flash-us
model="qwen3-asr-flash",
messages=messages,
result_format="message",
asr_options={
# "language": "zh", # Optional. If you know the language of the audio, you can use this parameter to specify the language to recognize, to improve recognition accuracy
"enable_itn":False
},
stream=True
)
for response in response:
try:
print(response["output"]["choices"][0]["message"].content[0]["text"])
except:
pass
Java SDK
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import io.reactivex.Flowable;
public class Main {
public static void simpleMultiModalConversationCall()
throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage userMessage = MultiModalMessage.builder()
.role(Role.USER.getValue())
.content(Arrays.asList(
Collections.singletonMap("audio", "{YOUR_AUDIO_URL}")))
.build();
Map<String, Object> asrOptions = new HashMap<>();
asrOptions.put("enable_itn", false);
// asrOptions.put("language", "zh"); // Optional. If you know the language of the audio, you can use this parameter to specify the language to recognize, to improve recognition accuracy
MultiModalConversationParam param = MultiModalConversationParam.builder()
// The API Key differs between the Singapore and Beijing regions. Get an API Key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// If you have not configured the environment variable, replace the following line with your Alibaba Cloud Model Studio API Key: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// If you use a model in the US region, add the "-us" suffix after the model name, for example, qwen3-asr-flash-us
.model("qwen3-asr-flash")
.message(userMessage)
.parameter("asr_options", asrOptions)
.build();
Flowable<MultiModalConversationResult> resultFlowable = conv.streamCall(param);
resultFlowable.blockingForEach(item -> {
try {
System.out.println(item.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
} catch (Exception e){
System.exit(0);
}
});
}
public static void main(String[] args) {
try {
// The following is the configuration for the Singapore region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
simpleMultiModalConversationCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
cURL
A configuração abaixo refere-se à região Singapore. Substitua {WorkspaceId} pelo seu Workspace ID real. A configuração varia conforme a região.
curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
"model": "qwen3-asr-flash",
"input": {
"messages": [
{
"content": [
{
"audio": "{YOUR_AUDIO_URL}"
}
],
"role": "user"
}
]
},
"parameters": {
"incremental_output": true,
"asr_options": {
"enable_itn": false
}
}
}'
Paraformer
O código de exemplo do Paraformer é semelhante à chamada assíncrona do Fun-ASR. Substitua o valor do modelo pelo nome de um modelo Paraformer.
Recursos avançados
Usar a API compatível com OpenAI
ImportanteA região US não oferece suporte ao modo compatível com OpenAI.
Somente os modelos da série Qwen3-ASR-Flash aceitam chamadas pelo modo compatível com OpenAI. Esse modo aceita apenas URLs de arquivos de áudio acessíveis publicamente e não permite o uso do caminho absoluto de um arquivo de áudio local.
Utilize o OpenAI Python SDK versão 1.52.0 ou superior, ou o Node.js SDK versão 4.68.0 ou superior. Para instalar ou atualizar o SDK, execute:
# Python
pip install -U "openai>=1.52.0"
# Node.js
npm install openai@^4.68.0
O parâmetro asr_options não faz parte do padrão OpenAI. Com o OpenAI Python SDK, passe-o por meio de extra_body. Já no Node.js OpenAI SDK, informe asr_options diretamente como um parâmetro de nível superior no corpo da requisição.
Entrada: URL do arquivo de áudio
Python SDK
from openai import OpenAI
import os
try:
client = OpenAI(
# The API Key differs between the Singapore/US regions and the Beijing region. Get an API Key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# If you have not configured the environment variable, replace the following line with your Alibaba Cloud Model Studio API Key: api_key = "sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following is the configuration for the Singapore region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
stream_enabled = False # Whether to enable streaming output
completion = client.chat.completions.create(
model="qwen3-asr-flash",
messages=[
{
"content": [
{
"type": "input_audio",
"input_audio": {
"data": "{YOUR_AUDIO_URL}"
}
}
],
"role": "user"
}
],
stream=stream_enabled,
# When stream is set to False, the stream_options parameter cannot be set
# stream_options={"include_usage": True},
extra_body={
"asr_options": {
# "language": "zh",
"enable_itn": False
}
}
)
if stream_enabled:
full_content = ""
print("The streaming output is:")
for chunk in completion:
# If stream_options.include_usage is True, the choices field of the last chunk is an empty list and needs to be skipped (you can get the Token usage via chunk.usage)
print(chunk)
if chunk.choices and chunk.choices[0].delta.content:
full_content += chunk.choices[0].delta.content
print(f"The complete content is: {full_content}")
else:
print(f"The non-streaming output is: {completion.choices[0].message.content}")
except Exception as e:
print(f"Error message: {e}")
Node.js SDK
// Preparations before running:
// Common to Windows/Mac/Linux:
// 1. Make sure Node.js is installed (version >= 14 recommended)
// 2. Run the following command to install the required dependencies: npm install openai
import OpenAI from "openai";
const client = new OpenAI({
// The API Key differs between the Singapore/US regions and the Beijing region. Get an API Key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// If you have not configured the environment variable, replace the following line with your Alibaba Cloud Model Studio API Key: apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
// The following is the configuration for the Singapore region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
});
async function main() {
try {
const streamEnabled = false; // Whether to enable streaming output
const completion = await client.chat.completions.create({
model: "qwen3-asr-flash",
messages: [
{
role: "user",
content: [
{
type: "input_audio",
input_audio: {
data: "{YOUR_AUDIO_URL}"
}
}
]
}
],
stream: streamEnabled,
// When stream is set to False, the stream_options parameter cannot be set
// stream_options: {
// "include_usage": true
// },
asr_options: {
// language: "zh",
enable_itn: false
}
});
if (streamEnabled) {
let fullContent = "";
console.log("The streaming output is:");
for await (const chunk of completion) {
console.log(JSON.stringify(chunk));
if (chunk.choices && chunk.choices.length > 0) {
const delta = chunk.choices[0].delta;
if (delta && delta.content) {
fullContent += delta.content;
}
}
}
console.log(`The complete content is: ${fullContent}`);
} else {
console.log(`The non-streaming output is: ${completion.choices[0].message.content}`);
}
} catch (err) {
console.error(`Error message: ${err}`);
}
}
main();
cURL
A configuração a seguir aplica-se à região de Singapore. Substitua {WorkspaceId} pelo seu Workspace ID real. A configuração varia conforme a região.
curl -X POST 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions' \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3-asr-flash",
"messages": [
{
"content": [
{
"type": "input_audio",
"input_audio": {
"data": "{YOUR_AUDIO_URL}"
}
}
],
"role": "user"
}
],
"stream":false,
"asr_options": {
"enable_itn": false
}
}'
Input: Base64-encoded audio file
Forneça os dados codificados em Base64 como uma Data URL no formato data:<mediatype>;base64,<data>.
-
<mediatype>: o tipo MIME.O tipo MIME varia de acordo com o formato do áudio. Por exemplo:
- WAV:
audio/wav - MP3:
audio/mpeg
- WAV:
-
<data>: a string do áudio codificada em Base64.A codificação Base64 aumenta o tamanho dos dados. Mantenha o arquivo source pequeno o suficiente para que o resultado codificado ainda respeite o limite de tamanho de áudio de entrada (10 MB).
-
Exemplo:
data:audio/wav;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA//PAxABQ/BXRbMPe4IQAhl9Click to view sample code
import base64, pathlib # input.mp3 is the local audio file used for voice cloning. Replace it with the path to your own audio file and make sure it meets the audio requirements. file_path = pathlib.Path("{YOUR_AUDIO_FILE}") base64_str = base64.b64encode(file_path.read_bytes()).decode() data_uri = f"data:audio/mpeg;base64,{base64_str}"import java.nio.file.*; import java.util.Base64; public class Main { /** * filePath is the local audio file used for voice cloning. Replace it with the path to your own audio file and make sure it meets the audio requirements. */ public static String toDataUrl(String filePath) throws Exception { byte[] bytes = Files.readAllBytes(Paths.get(filePath)); String encoded = Base64.getEncoder().encodeToString(bytes); return "data:audio/mpeg;base64," + encoded; } // Usage example public static void main(String[] args) throws Exception { System.out.println(toDataUrl("{YOUR_AUDIO_FILE}")); } }
import base64
from openai import OpenAI
import os
import pathlib
try:
# Replace with the actual audio file path
file_path = "{YOUR_AUDIO_FILE}"
# Replace with the actual MIME type of the audio file
audio_mime_type = "audio/mpeg"
file_path_obj = pathlib.Path(file_path)
if not file_path_obj.exists():
raise FileNotFoundError(f"Audio file does not exist: {file_path}")
base64_str = base64.b64encode(file_path_obj.read_bytes()).decode()
data_uri = f"data:{audio_mime_type};base64,{base64_str}"
client = OpenAI(
# The API Key differs between the Singapore/US regions and the Beijing region. Get an API Key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# If you have not configured the environment variable, replace the following line with your Alibaba Cloud Model Studio API Key: api_key = "sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following is the configuration for the Singapore region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
stream_enabled = False # Whether to enable streaming output
completion = client.chat.completions.create(
model="qwen3-asr-flash",
messages=[
{
"content": [
{
"type": "input_audio",
"input_audio": {
"data": data_uri
}
}
],
"role": "user"
}
],
stream=stream_enabled,
# When stream is set to False, the stream_options parameter cannot be set
# stream_options={"include_usage": True},
extra_body={
"asr_options": {
# "language": "zh",
"enable_itn": False
}
}
)
if stream_enabled:
full_content = ""
print("The streaming output is:")
for chunk in completion:
# If stream_options.include_usage is True, the choices field of the last chunk is an empty list and needs to be skipped (you can get the Token usage via chunk.usage)
print(chunk)
if chunk.choices and chunk.choices[0].delta.content:
full_content += chunk.choices[0].delta.content
print(f"The complete content is: {full_content}")
else:
print(f"The non-streaming output is: {completion.choices[0].message.content}")
except Exception as e:
print(f"Error message: {e}")
// Preparations before running:
// Common to Windows/Mac/Linux:
// 1. Make sure Node.js is installed (version >= 14 recommended)
// 2. Run the following command to install the required dependencies: npm install openai
import OpenAI from "openai";
import { readFileSync } from 'fs';
const client = new OpenAI({
// The API Key differs between the Singapore/US regions and the Beijing region. Get an API Key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// If you have not configured the environment variable, replace the following line with your Alibaba Cloud Model Studio API Key: apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
// The following is the configuration for the Singapore region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
});
const encodeAudioFile = (audioFilePath) => {
const audioFile = readFileSync(audioFilePath);
return audioFile.toString('base64');
};
// Replace with the actual audio file path
const dataUri = `data:audio/mpeg;base64,${encodeAudioFile("{YOUR_AUDIO_FILE}")}`;
async function main() {
try {
const streamEnabled = false; // Whether to enable streaming output
const completion = await client.chat.completions.create({
model: "qwen3-asr-flash",
messages: [
{
role: "user",
content: [
{
type: "input_audio",
input_audio: {
data: dataUri
}
}
]
}
],
stream: streamEnabled,
// When stream is set to False, the stream_options parameter cannot be set
// stream_options: {
// "include_usage": true
// },
asr_options: {
// language: "zh",
enable_itn: false
}
});
if (streamEnabled) {
let fullContent = "";
console.log("The streaming output is:");
for await (const chunk of completion) {
console.log(JSON.stringify(chunk));
if (chunk.choices && chunk.choices.length > 0) {
const delta = chunk.choices[0].delta;
if (delta && delta.content) {
fullContent += delta.content;
}
}
}
console.log(`The complete content is: ${fullContent}`);
} else {
console.log(`The non-streaming output is: ${completion.choices[0].message.content}`);
}
} catch (err) {
console.error(`Error message: ${err}`);
}
}
main();
Processamento de arquivos de áudio longos
O reconhecimento de fala não em tempo real permite a transcrição assíncrona de arquivos de áudio longos. Esse recurso é ideal para cenários como atas de reuniões, transcrições de entrevistas e reprodução de chamadas.
Limitações:- Qwen-Audio-3.0-ASR-Flash-Filetrans/Fun-ASR / Qwen3-ASR-Flash-Filetrans / Paraformer: um único arquivo de áudio pode ter até 2 GB de tamanho e 12 horas de duração.
- Qwen-Audio-3.0-ASR-Flash/Fun-ASR-Flash/Qwen3-ASR-Flash: um único arquivo de áudio pode ter até 10 MB de tamanho e 5 minutos de duração. Para áudios mais longos, utilize Qwen-Audio-3.0-ASR-Flash-Filetrans, Fun-ASR ou Qwen3-ASR-Flash-Filetrans.
- Com diarização de falantes ativada: mantenha a duração do áudio dentro de 2 horas. Áudios mais longos podem causar falhas no reconhecimento ou timeouts. Para mais informações, consulte Speaker diarization.
Fluxo de chamada: a transcrição de áudio longo utiliza um modelo de tarefa assíncrona com três etapas:
- Envie a tarefa de transcrição e obtenha um
task_id. - Consulte periodicamente a API de status da tarefa ou use o método de espera do SDK para bloquear a execução até que a tarefa seja concluída.
- Após a conclusão da tarefa, baixe o JSON com o resultado do reconhecimento a partir da URL retornada.
Para exemplos de código, consulte o código Quick start em Reconhecimento de fala não em tempo real.
Saída em streaming
Os modelos Qwen-Audio-3.0-ASR-Flash/Fun-ASR-Flash/Qwen3-ASR-Flash suportam saída em streaming, retornando resultados intermediários à medida que o reconhecimento avança. Essa abordagem atende bem a cenários que exigem feedback de progresso em tempo real.
Modelos de transcrição assíncrona, como Qwen-Audio-3.0-ASR-Flash-Filetrans, Fun-ASR, Qwen3-ASR-Flash-Filetrans e Paraformer, não oferecem suporte a saída em streaming. Obtenha o resultado final consultando a tarefa periodicamente (para mais detalhes, consulte Process long audio files).
Como ativar:- DashScope Python SDK: defina o parâmetro
streamcomoTrue. - DashScope Java SDK: chame a API
streamCall. - DashScope HTTP: defina o cabeçalho
X-DashScope-SSEcomoenable. - SDK compatível com OpenAI: defina o parâmetro
streamcomoTrue.
Para exemplos de código de saída em streaming, consulte a seção de reconhecimento de fala não em tempo real para Qwen3-ASR-Flash no Quick start.
Melhoria de precisão com hotwords
Hotwords aumentam a precisão do reconhecimento de substantivos próprios específicos de domínio, como nomes de pessoas, locais e produtos. Para detalhes sobre como criar e usar hotwords, consulte Improve recognition accuracy.
Cada SDK adota convenções de nomenclatura diferentes para esses parâmetros, como chaves de dicionário, propriedades de objeto ou métodos. Para o mapeamento completo dos campos, consulte a referência da API de cada SDK.
Melhoria de precisão com aprimoramento de contexto
O aprimoramento de contexto envia o histórico da conversa para o modelo ASR, o que melhora significativamente a precisão da transcrição de substantivos próprios. Para detalhes sobre como usar esse recurso e ver exemplos de resultados, consulte Context enhancement.
Diarização de falantes
A diarização de falantes identifica automaticamente os diferentes interlocutores no áudio e rotula cada frase no resultado da transcrição com uma tag de falante. Esse recurso é adequado para cenários como reuniões com múltiplos participantes e gravações de entrevistas.
Modelos suportados: séries Qwen-Audio-3.0-ASR-Flash-Filetrans, Fun-ASR e Paraformer.
Como ativar: defina o parâmetro diarization_enabled como true na requisição da API. No resultado, cada frase inclui um campo speaker_id que identifica o falante.
Exemplo de estrutura de retorno (trecho):
{
"transcripts": [
{
"sentences": [
{ "begin_time": 100, "end_time": 3820, "text": "Hello, let's discuss the project progress today.", "speaker_id": 0 },
{ "begin_time": 3820, "end_time": 6500, "text": "Sure, let me give a quick report first.", "speaker_id": 1 }
]
}
]
}
Os SDKs utilizam convenções de nomenclatura distintas para esses campos, como chaves de dicionário, propriedades de objeto ou métodos. Para o mapeamento completo dos campos, consulte a referência da API de cada SDK.
ImportanteAo ativar a diarização de falantes, mantenha a duração do áudio dentro de 2 horas. Áudios mais longos podem causar falhas no reconhecimento ou timeouts. Para os limites de duração de áudio com a diarização desativada, consulte Process long audio files. A diarização de falantes suporta apenas áudio mono.
Para as definições completas dos campos, consulte a referência da API.
Filtragem de palavras sensíveis
A filtragem de palavras sensíveis substitui ou remove termos sensíveis no resultado do reconhecimento. Essa funcionalidade é útil para cenários como inspeção de qualidade de atendimento ao cliente, conformidade de conteúdo e moderação de legendas.
Modelos suportados: séries Qwen-Audio-3.0-ASR-Flash-Filetrans, Fun-ASR e Paraformer.
Comportamento padrão: quando o parâmetro special_word_filter não é fornecido, o sistema utiliza a lista de palavras sensíveis do Model Studio integrada. As palavras correspondentes são substituídas por uma string de * de igual comprimento.
Configuração personalizada: special_word_filter é um objeto JSON com três subcampos:
filter_with_signed.word_list: um array de strings com palavras sensíveis a serem substituídas por uma sequência de*de igual comprimento. Por exemplo, com["test"], "Please help me test this" torna-se "Please help me **** this".filter_with_empty.word_list: um array de strings com palavras sensíveis a serem removidas completamente do resultado. Por exemplo, com["start"], "Is the game about to start now" torna-se "Is the game about to now".system_reserved_filter: um valor booleano cujo padrão étrue. Ele controla se a lista de palavras sensíveis integrada do sistema também deve ser aplicada, funcionando em conjunto com sua lista personalizada.
Exemplo de configuração:
{
"special_word_filter": {
"filter_with_signed": {
"word_list": ["test"]
},
"filter_with_empty": {
"word_list": ["start", "happen"]
},
"system_reserved_filter": true
}
}
Os SDKs adotam convenções de nomenclatura diferentes para esses parâmetros, como chaves de dicionário, propriedades de objeto ou métodos. Para o mapeamento completo dos campos, consulte a referência da API.
Reconhecimento de emoções
Os modelos das séries Qwen3-ASR-Flash-Filetrans e Qwen3-ASR-Flash possuem reconhecimento de emoções permanentemente ativado, sem necessidade de configuração adicional. O resultado inclui uma tag de emoção para o falante, escolhida entre sete emoções granulares: surprised, neutral, happy, sad, disgusted, angry e fearful.
Caminhos dos campos (variam conforme a API):
- API compatível com OpenAI (transcrição em tempo real do Qwen3-ASR-Flash): aninhado em
choices[].delta.annotations[].emotion(saída em streaming) ouchoices[].message.annotations[].emotion(sem streaming). - API síncrona do DashScope (Qwen3-ASR-Flash): aninhado em
output.choices[].message.annotations[].emotion. - API de tarefa assíncrona do DashScope (transcrição de arquivos gravados com Qwen3-ASR-Flash-Filetrans): aninhado em
transcripts[].sentences[].emotion, juntamente com o timestamp, falante e outros campos em cada objeto de frase.
Exemplo de estrutura de retorno (trecho da API de tarefa assíncrona do DashScope):
{
"transcripts": [{
"sentences": [{
"begin_time": 0,
"end_time": 1440,
"text": "Welcome to Alibaba Cloud.",
"emotion": "neutral",
"language": "en"
}]
}]
}
Os SDKs utilizam convenções de nomenclatura distintas para esses campos, como chaves de dicionário, propriedades de objeto ou métodos. Para o mapeamento completo dos campos, consulte a referência da API.
ImportanteOs modelos não em tempo real Qwen-Audio-3.0-ASR-Flash-Filetrans, Qwen-Audio-3.0-ASR-Flash, Fun-ASR-Flash, Fun-ASR e Paraformer não suportam reconhecimento de emoções. Para usar reconhecimento de emoções em tempo real, consulte a seção correspondente em Real-time speech recognition.
Obtenção de timestamps
O reconhecimento de fala não em tempo real pode gerar timestamps no resultado da transcrição, facilitando a geração de legendas, o destaque de palavras-chave e a edição de áudio/vídeo. Os modelos Qwen-Audio-3.0-ASR-Flash-Filetrans, Qwen-Audio-3.0-ASR-Flash, Fun-ASR, Fun-ASR-Flash, Qwen3-ASR-Flash-Filetrans e Paraformer suportam timestamps, mas o comportamento padrão e o método de controle variam conforme o modelo:
- Qwen-Audio-3.0-ASR-Flash-Filetrans/Qwen-Audio-3.0-ASR-Flash/Fun-ASR/Fun-ASR-Flash/Paraformer: os timestamps estão permanentemente ativados e não podem ser desligados.
- Qwen3-ASR-Flash-Filetrans: apenas a chamada assíncrona via DashScope suporta timestamps, que ficam permanentemente ativados. Utilize o parâmetro de requisição
enable_wordspara controlar o nível de detalhe do timestamp: defina-o comofalse(padrão) para retornar timestamps no nível da frase, outruepara retornar timestamps no nível da palavra. Timestamps no nível da palavra suportam apenas os seguintes idiomas: chinês, inglês, japonês, coreano, alemão, francês, espanhol, italiano, português e russo. A precisão não é garantida para outros idiomas.
ImportanteAo chamar o Qwen3-ASR-Flash através da API compatível com OpenAI, o formato de saída é chat.completion, que não retorna campos de timestamp. Para obter timestamps, utilize o Qwen3-ASR-Flash-Filetrans (a API de tarefa assíncrona).
Os timestamps são expressos em milissegundos e retornados em dois níveis:
- Nível da frase:
sentences[].begin_timeesentences[].end_timemarcam o início e o fim de cada frase no áudio. - Nível da palavra: o array
sentences[].words[], onde cada elemento contémbegin_time,end_timeetext(o texto daquela palavra).
Exemplo de estrutura de retorno (trecho da API de tarefa assíncrona do DashScope):
{
"transcripts": [{
"sentences": [{
"begin_time": 100,
"end_time": 3820,
"text": "Hello, let's discuss the project progress today.",
"words": [
{ "begin_time": 100, "end_time": 596, "text": "Hello," },
{ "begin_time": 596, "end_time": 844, "text": "let's" }
]
}]
}]
}
ImportanteO timestamp dentro do áudio é um número inteiro em milissegundos (como 100). Não o confunda com o end_time no nível da tarefa (o horário de conclusão da tarefa, uma string de data como "2024-09-12 15:11:40.903"). São campos distintos.
Os SDKs utilizam convenções de nomenclatura distintas para esses campos, como chaves de dicionário, propriedades de objeto ou métodos. Para o mapeamento completo dos campos, consulte a referência da API.
Aplicação em produção
Ao implementar o reconhecimento de fala não em tempo real em produção, as práticas recomendadas a seguir ajudam a melhorar a qualidade do reconhecimento e a estabilidade do sistema.
Cenários de alta concorrência: use callbacks em vez de polling
Para tarefas de transcrição assíncrona (Qwen-Audio-3.0-ASR-Flash-Filetrans, Fun-ASR, Qwen3-ASR-Flash-Filetrans e Paraformer), você envia a tarefa através de POST /api/v1/services/audio/asr/transcription e geralmente obtém o resultado chamando periodicamente a API de consulta GET /api/v1/tasks/{task_id}. Essa API de consulta tem um padrão de 20 QPS, escalável até 100 QPS. Em cenários de lote com alta concorrência, o polling frequente aciona facilmente limitações de taxa.
Configure notificações de callback via EventBridge. Quando uma tarefa é concluída, o Model Studio envia automaticamente um evento dashscope:System:AsyncTaskFinish para o destino configurado (um endpoint HTTP/HTTPS ou um tópico RocketMQ). Após receber o evento, o consumidor não precisa mais chamar a API de consulta, evitando o risco de limitação por polling frequente. Para mais informações, consulte Configure EventBridge callback notifications.
Modelos suportados
- Suportados: Qwen-Audio-3.0-ASR-Flash-Filetrans, Fun-ASR, Qwen3-ASR-Flash-Filetrans e Paraformer (todas as tarefas de transcrição assíncrona).
- Não suportados: Qwen3-ASR-Flash (chamadas síncronas ou em streaming, que não são tarefas assíncronas).
Conteúdo da mensagem de callback
Para todos os três modelos, o corpo da mensagem de callback possui data.contain_result definido como true, e data.output_result carrega diretamente a transcription_url. Ao receber o callback, o consumidor pode obter o resultado do reconhecimento sem precisar chamar GET /api/v1/tasks/{task_id} novamente. No entanto, o caminho e a estrutura do campo de resultado diferem entre os três modelos. Consulte a tabela abaixo.
ObservaçãoAo desenvolver o consumidor, escolha o caminho correto para o modelo utilizado. Evite codificar um único caminho fixo. Em cenários de falha, data.output_result.output deixa de conter results/result; em vez disso, passa a conter os campos code e message. Verifique primeiro data.task_status antes de ler o resultado.
Modelo | Parâmetro de envio | Caminho do campo de resultado (baseado no corpo do callback) | Campo usage |
|---|---|---|---|
Qwen-Audio-3.0-ASR-Flash-Filetrans, Fun-ASR |
|
|
|
Paraformer |
| Igual ao Qwen-Audio-3.0-ASR-Flash-Filetrans/Fun-ASR: |
|
Qwen3-ASR-Flash-Filetrans |
|
|
|
Notas de uso
Segurança (entrega HTTP/HTTPS): em produção, valide os campos de cabeçalho X-Eventbridge-Signature* na requisição de callback antes de consumi-la. Caso contrário, qualquer IP externo pode forjar um evento AsyncTaskFinish e injetar resultados falsos de reconhecimento. Defina também um timeout de recebimento de pelo menos 5 segundos no receptor. O método de entrega via RocketMQ não possui assinatura no nível da mensagem; sua segurança é garantida pelo mecanismo de autenticação do próprio RocketMQ.
Latência de entrega: desde a conclusão da tarefa (end_time) até o momento em que o destino da entrega (um endpoint HTTP/HTTPS ou um tópico RocketMQ) recebe a mensagem, o atraso costuma variar entre 1 e 90 segundos. A latência exata depende da carga em tempo real do EventBridge.
Idempotência: o mesmo evento pode ser entregue múltiplas vezes devido a retries. Implemente processamento idempotente no consumidor, utilizando CloudEvents data.id ou data.task_id como chave de deduplicação.
Recomendações para produção
- Hospedagem de arquivos: carregue os arquivos de áudio no Alibaba Cloud OSS e chame a API via URL. Evite uploads de arquivos locais (chamadas com arquivos locais têm limite de 100 QPS e não podem ser escaladas).
- Polling assíncrono: a transcrição de áudio longo utiliza um modelo assíncrono. Defina um intervalo de polling razoável (como 2 a 5 segundos) para evitar consultas frequentes que consomem sua cota. Para ultrapassar o limite de consulta de 20 a 100 QPS, mude para notificações de callback de eventos. Para mais informações, consulte High-concurrency scenarios: use callbacks instead of polling.
- Tratamento de erros: implemente um mecanismo robusto de retry. Para timeouts de rede ou erros temporários no servidor (5xx), tente novamente usando uma estratégia de backoff exponencial.
- Redução de ruído: para áudios com muito ruído, faça um pré-processamento com ferramentas como FFmpeg antes de enviá-los para reconhecimento.
- Seleção de modelo: escolha o modelo adequado com base na duração do áudio. Para áudios curtos de até 5 minutos, utilize Qwen3-ASR-Flash. Para áudios longos com mais de 5 minutos, prefira Qwen-Audio-3.0-ASR-Flash-Filetrans, Fun-ASR ou Qwen3-ASR-Flash-Filetrans.
Modelos e regiões suportados
Singapore
Para chamar os modelos a seguir, utilize uma API Key da região de Singapore:
- Qwen-Audio-3.0-ASR-Flash-Filetrans: qwen-audio-3.0-asr-flash-filetrans
- Qwen-Audio-3.0-ASR-Flash: qwen-audio-3.0-asr-flash
- Fun-ASR: fun-asr (versão estável, atualmente equivalente a fun-asr-2025-11-07), fun-asr-2025-11-07 (versão snapshot), fun-asr-2025-08-25 (versão snapshot), fun-asr-mtl (versão estável, atualmente equivalente a fun-asr-mtl-2025-08-25), fun-asr-mtl-2025-08-25 (versão snapshot)
- Fun-ASR-Flash: fun-asr-flash-2026-06-15
- Qwen3-ASR-Flash-Filetrans: qwen3-asr-flash-filetrans (versão estável, atualmente equivalente a qwen3-asr-flash-filetrans-2025-11-17), qwen3-asr-flash-filetrans-2025-11-17 (versão snapshot)
- Qwen3-ASR-Flash: qwen3-asr-flash (versão estável, atualmente equivalente a qwen3-asr-flash-2025-09-08), qwen3-asr-flash-2026-02-10 (versão snapshot mais recente), qwen3-asr-flash-2025-09-08 (versão snapshot)
US (Virginia)
Para chamar os modelos a seguir, utilize uma API Key da região dos EUA:
Qwen3-ASR-Flash: qwen3-asr-flash-us (versão estável, atualmente equivalente a qwen3-asr-flash-2025-09-08-us), qwen3-asr-flash-2025-09-08-us (versão snapshot)
China (Beijing)
Para chamar os modelos a seguir, utilize uma API Key da região de Beijing:
- Qwen-Audio-3.0-ASR-Flash-Filetrans: qwen-audio-3.0-asr-flash-filetrans
- Qwen-Audio-3.0-ASR-Flash: qwen-audio-3.0-asr-flash
- Fun-ASR: fun-asr (versão estável, atualmente equivalente a fun-asr-2025-11-07), fun-asr-2025-11-07 (versão snapshot), fun-asr-2025-08-25 (versão snapshot), fun-asr-mtl (versão estável, atualmente equivalente a fun-asr-mtl-2025-08-25), fun-asr-mtl-2025-08-25 (versão snapshot)
- Fun-ASR-Flash: fun-asr-flash-2026-06-15
- Qwen3-ASR-Flash-Filetrans: qwen3-asr-flash-filetrans (versão estável, atualmente equivalente a qwen3-asr-flash-filetrans-2025-11-17), qwen3-asr-flash-filetrans-2025-11-17 (versão snapshot)
- Qwen3-ASR-Flash: qwen3-asr-flash (versão estável, atualmente equivalente a qwen3-asr-flash-2025-09-08), qwen3-asr-flash-2026-02-10 (versão snapshot mais recente), qwen3-asr-flash-2025-09-08 (versão snapshot)
- Paraformer: paraformer-v2, paraformer-8k-v2
Referência da API
- Non-real-time speech recognition - Qwen-Audio-3.0-ASR-Flash-Filetrans/Fun-ASR API reference
- Non-real-time speech recognition - Qwen-Audio-3.0-ASR-Flash/Fun-ASR-Flash API reference
- Non-real-time speech recognition - Qwen-ASR API reference
- Non-real-time speech recognition - Paraformer API reference
FAQ
P: Como forneço uma URL de áudio publicamente acessível para a API?
Utilize o Alibaba Cloud Object Storage Service (OSS). O OSS oferece armazenamento altamente disponível e confiável, além de permitir a geração de uma URL de acesso público.
Verifique se a URL gerada é acessível pela rede pública: abra a URL em um navegador ou com o comando curl para confirmar que o arquivo de áudio é baixado ou reproduzido (código de status HTTP 200).
P: Como verifico se o formato de áudio atende aos requisitos?
Utilize a ferramenta de código aberto ffprobe para obter rapidamente informações detalhadas sobre o áudio:
# Query the container format (format_name), codec (codec_name), sample rate (sample_rate), and number of channels (channels) of the audio
ffprobe -v error -show_entries format=format_name -show_entries stream=codec_name,sample_rate,channels -of default=noprint_wrappers=1 your_audio_file.mp3
P: Como processo o áudio para atender aos requisitos do modelo?
Utilize a ferramenta de código aberto FFmpeg para recortar ou converter o áudio:
- Recortar áudio: extrair um trecho de um arquivo de áudio longo
# -i: input file
# -ss 00:01:30: set the trim start time (start at 1 minute 30 seconds)
# -t 00:02:00: set the trim duration (trim 2 minutes)
# -c copy: copy the audio stream directly without re-encoding, which is fast
# output_clip.wav: output file
ffmpeg -i long_audio.wav -ss 00:01:30 -t 00:02:00 -c copy output_clip.wav
-
Converter o formato
Por exemplo, converta qualquer áudio para um arquivo WAV mono, 16 bits e 16 kHz:
# -i: input file
# -ac 1: set the number of channels to 1 (mono)
# -ar 16000: set the sample rate to 16000 Hz (16 kHz)
# -sample_fmt s16: set the sample format to 16-bit signed integer PCM
# output.wav: output file
ffmpeg -i input.mp3 -ac 1 -ar 16000 -sample_fmt s16 output.wav
P: Como melhorar a precisão do reconhecimento?
Os fatores a seguir afetam a precisão do reconhecimento. Verifique cada um e otimize conforme necessário.
Principais fatores:
- Qualidade do áudio: a qualidade do dispositivo de gravação, a taxa de amostragem e o ruído ambiental afetam diretamente a clareza do áudio. Uma entrada de áudio de alta qualidade é a base para um reconhecimento preciso.
- Características do falante: tom de voz, velocidade de fala, sotaque e diferenças de dialeto (especialmente dialetos raros ou sotaques fortes) aumentam a dificuldade de reconhecimento.
- Idioma e vocabulário: mistura de idiomas, termos técnicos ou gírias aumentam a dificuldade de reconhecimento. Configure hotwords para melhorar a precisão de termos específicos do domínio.
Métodos de otimização:
- Melhore a qualidade do áudio: use um microfone de alto desempenho, grave na taxa de amostragem recomendada e minimize o ruído ambiental e o eco.
- Adapte-se ao falante: para áudios com sotaques fortes ou dialetos notáveis, escolha um modelo que suporte o dialeto correspondente.
- Configure hotwords: defina hotwords para termos técnicos, nomes próprios e palavras semelhantes.