前提条件
- 已开通服务并获取与配置 API Key。请配置API Key到环境变量,而非硬编码在代码中,防范因代码泄露导致的安全风险。
- 安装最新版DashScope SDK。
接口地址 — Qwen-Audio-ASR-Streaming / Fun-ASR-Realtime
SDK的实时识别走WebSocket接口,端点由Client的workspace与region自动决定(包含WorkspaceId)。如需切换到其他地域,构造Client时设置对应地域的region即可。
新加坡
wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference
调用时请将{WorkspaceId}替换为真实的Workspace ID。
华北2(北京)
wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference
调用时请将{WorkspaceId}替换为真实的Workspace ID。
重要阿里云百炼为华北2(北京)、新加坡地域推出了业务空间专属域名,能够为推理请求提供卓越的性能和更高的稳定性,建议迁移至新域名:
- 华北2(北京)地域:从
dashscope.aliyuncs.com迁移至{WorkspaceId}.cn-beijing.maas.aliyuncs.com - 新加坡地域:从
dashscope-intl.aliyuncs.com迁移至{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com
快速開始
將 {WorkspaceId} 替換為您的業務空間 ID,並將 {YOUR_AUDIO_FILE} 替換為本機 16 kHz WAV 檔案的路徑。該範例會在終端機中輸出轉錄結果。
import os
import dashscope
# If you have not configured the environment variable, replace the following line with your Model Studio API Key: api_key="sk-xxx"
client = dashscope.Client(
api_key=os.environ.get('DASHSCOPE_API_KEY'),
# The following is the configuration for the Singapore (ap-southeast-1) region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
# Recognize a local audio file: recognize_file automatically sends the audio in chunks and drives the task to completion
for event in client.audio.asr.recognize_file(
'{YOUR_AUDIO_FILE}',
model='fun-asr-realtime',
format='wav',
sample_rate=16000):
payload = event.get('payload') or {}
sentence = (payload.get('output') or {}).get('sentence') or {}
if sentence.get('text') and not sentence.get('heartbeat'):
print('识别结果:', sentence['text'])
其他範例
以下呼叫範例為多個模型共用。請依下表替換範例中的模型 ID。
| 模型 | 範例中的模型 ID |
|---|---|
| Qwen-Audio-ASR-Streaming | qwen-audio-3.1-asr-flash-streaming麥克風範例使用 qwen-audio-3.0-asr-flash-streaming。 |
| Qwen-Audio-ASR-Message | qwen-audio-3.1-asr-flash-message僅支援 16000 Hz 取樣率。 |
| Fun-ASR-Realtime | fun-asr-realtime |
核心資源 (client.audio.asr) 提供非串流呼叫與雙向串流呼叫等介面。請根據實際需求選擇合適的呼叫方式:
- 非串流呼叫 (
recognize_file):對本機檔案執行辨識;SDK 會自動將音訊分塊傳送並驅動任務完成。適合處理錄音檔案。 - 雙向串流呼叫 (
recognize工作階段):直接對音訊串流執行辨識並即時輸出結果。音訊串流可來自外部裝置(如麥克風),也可從本機檔案讀取。適合需要即時回饋的情境。
非串流呼叫
傳入本機檔案,提交單次即時語音轉錄任務,並以阻塞方式同步取得轉錄結果。
呼叫核心資源 (client.audio.asr) 的 recognize_file 方法繫結請求參數並傳入本機檔案路徑,再透過迭代伺服器端事件取得辨識結果。
import os
import dashscope
# The API Key differs between the Singapore and Beijing regions. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
# If you have not configured the environment variable, replace the following line with your Model Studio API Key: api_key="sk-xxx"
client = dashscope.Client(
api_key=os.environ.get('DASHSCOPE_API_KEY'),
# The following is the configuration for the Singapore (ap-southeast-1) region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
# Recognize a local audio file: recognize_file automatically sends the audio in chunks and drives the task to completion
for event in client.audio.asr.recognize_file(
'{YOUR_AUDIO_FILE}',
model='qwen-audio-3.1-asr-flash-streaming',
format='wav',
sample_rate=16000):
payload = event.get('payload') or {}
sentence = (payload.get('output') or {}).get('sentence') or {}
if sentence.get('text') and not sentence.get('heartbeat'):
print('识别结果:', sentence['text'])
雙向串流呼叫
提交單次即時語音轉錄任務,透過迭代事件串流輸出即時辨識結果。
-
開始串流語音辨識
呼叫核心資源 (
client.audio.asr) 的recognize方法建立辨識工作階段並繫結請求參數,然後進入with上下文(會自動呼叫start方法建立連線並傳送任務),開始串流語音辨識。 -
串流
循環呼叫工作階段的
send_audio_frame方法,將從本機檔案或裝置(如麥克風)讀取的二進位音訊串流分段傳送至伺服器。傳送與接收必須並行進行:接收執行緒透過工作階段的events()方法迭代伺服器端事件,並即時將辨識結果傳回用戶端。建議每次傳送的音訊時長約 100 毫秒,資料大小保持在 1 KB 至 16 KB 之間。
-
結束處理
呼叫工作階段的
stop方法結束語音辨識。此方法僅通知伺服器輸入已結束;接收執行緒必須繼續消費
events()直到task-finished事件,才能取得最終辨識結果與統計資訊。ws 層的錯誤會以DashScopeError例外拋出,您可在傳送或接收處使用 try/except 捕捉。
import os
import signal # for keyboard events handling (press "Ctrl+C" to terminate recording)
import sys
import dashscope
import pyaudio
from concurrent.futures import ThreadPoolExecutor
mic = None
stream = None
# Set recording parameters
sample_rate = 16000 # 麦克风与请求使用相同的采样率。Qwen-Audio-ASR-Message 仅支持 16000 Hz。
channels = 1 # mono channel
dtype = 'int16' # data type
format_pcm = 'pcm' # the format of the audio data
block_size = 3200 # number of frames per buffer
# Real-time speech recognition event receiver
def receive_events(rec):
for event in rec.events():
payload = event.get('payload') or {}
sentence = (payload.get('output') or {}).get('sentence') or {}
if sentence.get('text') and not sentence.get('heartbeat'):
print('Recognition text: ', sentence['text'])
if sentence.get('sentence_end'):
print(
'Recognition sentence end, request_id:%s, usage:%s'
% (rec.request_id, rec.usage))
def signal_handler(sig, frame):
print('Ctrl+C pressed, stop recognition ...')
# Stop recognition
recognition.stop()
print('Recognition stopped.')
print(
'[Metric] requestId: {}, first package delay ms: {}, last package delay ms: {}'
.format(
recognition.request_id,
recognition.first_package_delay,
recognition.last_package_delay,
))
# Forcefully exit the program
sys.exit(0)
# main function
if __name__ == '__main__':
# The API Key differs between the Singapore and Beijing regions. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
# If you have not configured the environment variable, replace the following line with your Model Studio API Key: api_key="sk-xxx"
client = dashscope.Client(
api_key=os.environ.get('DASHSCOPE_API_KEY'),
# The following is the configuration for the Singapore (ap-southeast-1) region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
# Call recognition service, you can customize the recognition parameters, like model, format,
# sample_rate
with client.audio.asr.recognize(
model='qwen-audio-3.0-asr-flash-streaming',
format=format_pcm,
# 'pcm'、'wav'、'opus'、'speex'、'aac'、'amr', you can check the supported formats in the document
sample_rate=sample_rate,
) as recognition:
# Open the microphone
mic = pyaudio.PyAudio()
stream = mic.open(format=pyaudio.paInt16,
channels=1,
rate=sample_rate,
input=True)
with ThreadPoolExecutor(max_workers=1) as pool:
receiver = pool.submit(receive_events, recognition)
try:
# Send audio from the microphone until "Ctrl+C" is pressed
while stream:
data = stream.read(3200, exception_on_overflow=False)
recognition.send_audio_frame(data)
recognition.stop()
receiver.result()
finally:
# close must run inside the pool context to unblock the receiver
recognition.close()
stream.stop_stream()
stream.close()
mic.terminate()
stream = None
mic = None
import os
import time
import dashscope
from concurrent.futures import ThreadPoolExecutor
# The API Key differs between the Singapore and Beijing regions. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
# If you have not configured the environment variable, replace the following line with your Model Studio API Key: api_key="sk-xxx"
client = dashscope.Client(
api_key=os.environ.get('DASHSCOPE_API_KEY'),
# The following is the configuration for the Singapore (ap-southeast-1) region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
from datetime import datetime
def get_timestamp():
now = datetime.now()
formatted_timestamp = now.strftime("[%Y-%m-%d %H:%M:%S.%f]")
return formatted_timestamp
# Real-time speech recognition event receiver
def receive_events(rec):
for event in rec.events():
payload = event.get('payload') or {}
sentence = (payload.get('output') or {}).get('sentence') or {}
if sentence.get('text') and not sentence.get('heartbeat'):
print(get_timestamp() + ' Recognition text: ', sentence['text'])
if sentence.get('sentence_end'):
print(get_timestamp() +
'Recognition sentence end, request_id:%s, usage:%s'
% (rec.request_id, rec.usage))
with client.audio.asr.recognize(
model='qwen-audio-3.1-asr-flash-streaming',
format='wav',
sample_rate=16000,
) as recognition:
with ThreadPoolExecutor(max_workers=1) as pool:
receiver = pool.submit(receive_events, recognition)
try:
audio_data: bytes = None
f = open("{YOUR_AUDIO_FILE}", 'rb')
if os.path.getsize("{YOUR_AUDIO_FILE}"):
# Read all the file data into the buffer at once
file_buffer = f.read()
f.close()
print("Start Recognition")
# Send 3200 bytes from the buffer at a time
buffer_size = len(file_buffer)
offset = 0
chunk_size = 3200
while offset < buffer_size:
# Calculate the size of the data chunk to send this time
remaining_bytes = buffer_size - offset
current_chunk_size = min(chunk_size, remaining_bytes)
# Extract the current data chunk from the buffer
audio_data = file_buffer[offset:offset + current_chunk_size]
# Send the audio data frame
recognition.send_audio_frame(audio_data)
# Update the offset
offset += current_chunk_size
# Add a delay to simulate real-time transmission
time.sleep(0.1)
recognition.stop()
receiver.result()
else:
raise Exception(
'The supplied file was empty (zero bytes long)')
finally:
# close must run inside the pool context to unblock the receiver
recognition.close()
print(
'[Metric] requestId: {}, first package delay ms: {}, last package delay ms: {}'
.format(
recognition.request_id,
recognition.first_package_delay,
recognition.last_package_delay,
))
請求參數
Fun-ASR-Realtime
共用說明
請參閱新版 Fun-ASR-Realtime Python SDK。
請求參數透過核心資源 (client.audio.asr) 的 recognize/recognize_file 方法設定:model、format、sample_rate、vocabulary_id 可直接傳入;max_sentence_silence 和 language_hints 則透過 parameters 字典傳入。
| 參數 | 類型 | 必要 | 描述 |
|---|---|---|---|
model | str | 是 | 模型名稱。 |
sample_rate | int | 是 | 取樣率 (Hz)。 數值範圍:8k 模型僅支援 8000 Hz;其他模型支援任意取樣率。 |
format | str | 是 | 音訊格式。 有效值:
重要opus/speex:必須使用 Ogg 封裝; wav:必須使用 PCM 編碼; amr:僅支援 AMR-NB 類型。 |
vocabulary_id | str | 否 | 預先編譯的熱詞表 ID。 您必須事先呼叫熱詞表建立 API 產生該 ID;辨識時傳入此 ID 即可使用詞表中的熱詞。 適用於詞彙已知且相對穩定、需要在多次請求間重複使用同一詞彙的情境。 使用說明請參閱預先編譯熱詞。 |
max_sentence_silence | int | 否 | 用於斷句的 VAD 靜音閾值 (ms)。當一段語音後的靜音超過此閾值時,系統會判定該句已結束。 預設值:1300。 數值範圍:[200, 6000]。 |
multi_threshold_mode_enabled | bool | 否 | 是否啟用多閾值模式。啟用後可防止 VAD 斷句切割出過長的段落。 預設值:False。 |
punctuation_prediction_enabled | bool | 否 | 設定是否自動為辨識結果添加標點符號:
|
heartbeat | bool | 否 | 是否啟用心跳封包。 預設值:False。
靜音音訊是指音訊檔案或資料流中沒有聲音訊號的內容。靜音音訊可以透過多種方式產生,例如使用 Audacity 或 Adobe Audition 等音訊編輯軟體,或 FFmpeg 等命令列工具。 使用此欄位時,SDK 版本必須為 2.0.1 或以上。 |
language_hints | list[str] | 否 | 待辨識音訊的語言。沒有預設值;未設定時模型會自動辨識語言。 只能設定一個值;設定多個值時,僅第一個值生效 點擊查看支援的語言代碼
|
speech_noise_threshold | float | 否 | 用於區分語音與雜訊的閾值,用以調整語音活動偵測(VAD)的靈敏度。 取值範圍:[-1.0, 1.0]。 數值說明:
此為進階設定參數,調整後可能顯著影響辨識效能。建議:
|
special_word_filter | str | 否 | 指定語音辨識過程中需處理的敏感詞,並支援為不同敏感詞設定不同的處理方式。詳情請參閱敏感詞過濾。 |
使用 recognize 建立辨識工作階段時,可透過 input 傳入上下文。
| 參數 | 類型 | 必要 | 描述 |
|---|---|---|---|
input | dict | 否 | 輸入物件,用於傳入對話上下文。上下文有助於辨識,並可提升專有詞彙的辨識準確率。使用詳情請參閱提升辨識準確率。 重要僅 dict 必須包含
重要上下文訊息 ( 重要提供上下文時, 說明使用此欄位時,SDK 版本必須為 2.0.1 或以上。 |
API 參考
Qwen-Audio-ASR-Streaming / Fun-ASR-Realtime
辨識結果 (RecognitionResult)
RecognitionResult 表示工作階段 results() 每次迭代產生的辨識結果幀 (雙向串流與非串流呼叫皆可使用;events() 產生的是原始事件 dict —若需要此型別化檢視,請改用 results())。
| 成員方法 | 方法簽章 | 描述 |
|---|---|---|
get_sentence | | 取得目前辨識到的句子及其時間戳資訊。此方法回傳 Dict[str, Any] (句子資訊)。 詳情請參閱句子資訊。 |
request_id | | 當前事件對應請求的 request_id。 |
is_sentence_end | | 判斷當前句子是否已結束。此方法會檢查 get_sentence() 回傳的單句資訊中 end_time 欄位是否為 None —當 end_time 不為 None 時,表示句子已結束。 |
單句資訊 (Sentence)
Sentence 類別的成員如下:
| 參數 | 類型 | 描述 |
|---|---|---|
begin_time | int | 句子開始時間,單位為 ms。 |
end_time | int | 句子結束時間,單位為 ms。 |
text | str | 辨識出的文字。 |
words | 詞級時間戳記資訊 (Word)清單集合 | 詞級時間戳記資訊。 |
詞級時間戳記資訊 (Word)
Word类成员如下:
| 参数 | 类型 | 说明 |
|---|---|---|
begin_time | int | 字开始时间,单位为ms。 |
end_time | int | 字结束时间,单位为ms。 |
text | str | 字。 |
punctuation | str | 标点。 |
Fun-ASR-Realtime
關鍵介面
核心資源 (client.audio.asr)
即時語音辨識能力掛載於 client.audio.asr 資源:recognize 建立雙向串流辨識工作階段 (Recognition),recognize_file 則對本機檔案執行一次性辨識。
| 成員方法 | 方法簽章 | 描述 |
|---|---|---|
recognize | | 建立雙向串流辨識工作階段。進入 with 上下文時會自動呼叫 start 以建立連線並傳送任務。傳送音訊與消費事件必須並行進行 (需與 |
recognize_file | | 基於本機檔案的非串流呼叫:自動分塊傳送音訊並驅動任務直至完成,逐一產生伺服器端事件。此方法需要待辨識檔案的讀取權限。 |
start | | 啟動語音辨識:建立連線、傳送任務並等待 task-started。進入 with 上下文時會自動呼叫;只有在成功啟動後才能傳送音訊。 |
send_audio_frame | | 推送音訊。每次推送的音訊串流不宜過大或過小;建議每個音訊封包時長約 100ms、大小介於 1KB 至 16KB 之間。 辨識結果透過迭代 |
stop | | 停止語音辨識:僅通知伺服器輸入已結束;接收執行緒必須繼續消費 events(),直到 task-finished 事件為止。 |
events / results | | 逐一迭代服務端事件:events() 產生原始事件 dict (辨識文字位於 payload.output.sentence);results() 僅產生辨識結果幀,回傳帶類型的 辨識結果 (RecognitionResult) 物件 (心跳幀已被過濾)。 |
close | | 關閉辨識工作階段。離開 with 上下文時會自動呼叫。 |
request_id / first_package_delay / last_package_delay / last_response | | 取得 request_id、首包延遲 (從傳送第一個音訊分塊到收到第一個辨識結果的延遲) 與末包延遲 (從傳送 stop 命令到送達最後一個辨識結果的時間);請在工作完成後使用這些屬性。last_response 是最近一次成功讀取的原始訊息,可用於擷取工作失敗的錯誤。工作階段關閉後仍可讀取。 |
事件迭代 (events()/results())
在雙向串流呼叫期間,伺服器會以事件形式向用戶端回傳關鍵流程資訊與資料。您需要在接收執行緒中迭代工作階段的 events() (原始事件 dict) 或 results() (帶類型的辨識結果幀),以處理伺服器回傳的資訊或資料。
# 迭代原始事件:识别文本位于 payload.output.sentence
def receive_events(rec):
for event in rec.events():
payload = event.get('payload') or {}
sentence = (payload.get('output') or {}).get('sentence') or {}
if sentence.get('text') and not sentence.get('heartbeat'):
print('识别文本:', sentence['text'])
# 或只迭代识别结果帧(返回 RecognitionResult,心跳帧已过滤)
def receive_results(rec):
for result in rec.results():
sentence = result.get_sentence()
if sentence and 'text' in sentence:
print('识别文本:', sentence['text'])
| 事件/迭代方法 | 輸出 | 傳回值 | 描述 |
|---|---|---|---|
|
| None | 由 |
|
| 迭代器 | 當伺服器有回應時產生事件。辨識結果位於 |
|
| 迭代器 | 僅產生辨識結果幀 (心跳幀已過濾);所有辨識結果回傳完畢後迭代結束。 |
|
| None | 發生例外時在傳送/接收執行緒中拋出;可用 try/except 捕捉。 |
|
| None | 伺服器完成所有辨識後由 |
回應結果
错误码
如遇报错问题,请参见错误码进行排查。
若问题仍未解决,可加入语音 SDK 示例仓库中列出的开发者群反馈问题,并提供Request ID,以便进一步排查问题。