前提条件
- 已开通服务并获取与配置 API Key。请配置API Key到环境变量,而非硬编码在代码中,防范因代码泄露导致的安全风险。
- 安装最新版DashScope SDK。
API 端點 — Qwen-Audio-ASR-Message
SDK 中的即時辨識使用 WebSocket 介面,端點由 Client 的 workspace 和 region(包含 WorkspaceId)自動決定。如需切換至其他地域,請在建構 Client 時將 region 設定為對應地域。
新加坡
wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference
呼叫時請將 {WorkspaceId} 替換為您實際的 Workspace ID。
中國(北京)
wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference
呼叫時請將 {WorkspaceId} 替換為您實際的 Workspace ID。
日本(東京)
wss://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/api-ws/v1/inference
呼叫時請將 {WorkspaceId} 替換為您實際的 Workspace ID。
重要阿里雲 Model Studio 已為中國(北京)和新加坡地域推出業務空間專屬網域名稱,可為推理請求提供更優異的效能與更高的穩定性。我們建議您遷移至新網域名稱:
- 中國(北京)地域:從
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='qwen-audio-3.1-asr-flash-message',
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 之間。
-
結束處理
呼叫 session 的
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,
))
請求參數
Qwen-Audio-ASR-Message
共用說明
請參閱新版的 Qwen-Audio-ASR-Message Python SDK。
請求參數透過核心資源 (client.audio.asr)的 recognize/recognize_file 方法設定:model、format、sample_rate、vocabulary_id 可直接傳入;language_hints 則透過 parameters 字典傳入。
| 參數 | 類型 | 是否必填 | 描述 |
|---|---|---|---|
model | str | 是 | 模型名稱,設為 qwen-audio-3.1-asr-flash-message。 |
sample_rate | int | 是 | 取樣率 (Hz)。 僅支援 |
format | str | 是 | 音訊格式。 有效值:
重要opus/speex:必須使用 Ogg 封裝; wav:必須使用 PCM 編碼; amr:僅支援 AMR-NB 類型。 |
disfluency_removal_enabled | bool | 否 | 是否過濾語氣詞並潤色輸出結果,預設值為 false。設定為 true 時啟用。以同名關鍵字參數傳入。 |
intermediate_result_enabled | bool | 否 | 是否回傳串流中間結果。預設值為 false。設定為 true 時,會回傳串流中間結果。透過 parameters 字典傳入。 |
keep_dialect | bool | 否 | 預設值為 false,將方言轉寫為國語;設為 true 時,會保留方言表達方式。請透過 parameters 字典傳入。完整參數說明請參閱客戶端事件。僅對最終結果( |
vad_model | str | 否 | 可選值:near_meeting_16k (近場) 或 far_field_meeting_16k (遠場,預設值)。請透過 parameters 字典傳入。完整參數說明請參閱客戶端事件。 |
vocabulary_id | str | 否 | 預先編譯的熱詞列表 ID。 需事先呼叫熱詞列表建立 API 產生該 ID;在辨識時傳入此 ID,即可使用列表中的熱詞。 適用於詞彙已知且相對穩定、需要在多次請求間重複使用同一詞表的情境。 使用說明請參見預先編譯熱詞。 |
vocabulary | dict | 否 | 即時熱詞。 以鍵值對形式傳入,鍵為熱詞文字( 適用於臨時的、工作階段層級的熱詞最佳化。 與預先編譯熱詞同時設定時,系統會合併兩類熱詞;若合併後總數超過 2000,將隨機選取 2000 個使用。使用說明請參見即時熱詞。 範例: |
language_hints | list[str] | 否 | 待辨識音訊的語言。無預設值;未設定時由模型自動辨識。 最多可設定 4 個值;若超過,僅前 4 個生效。 點擊查看支援的語言代碼
透過 僅對最終結果( |
max_sentence_silence | int | 否 | 用於斷句的 VAD 靜音閾值(毫秒)。當一段語音後的靜音時長超過該閾值時,系統判定該句子已結束。 預設值:800。 取值範圍:[200, 6000]。 |
heartbeat | bool | 否 | 是否啟用心跳封包。 預設值:False。
靜音音訊指音訊檔案或資料流中不含聲音訊號的內容。靜音音訊可以透過多種方式產生,例如使用 Audacity 或 Adobe Audition 等音訊編輯軟體,或 FFmpeg 等命令列工具。 此欄位於 SDK 1.23.1 引入,並包含於 2.0.1 及之後版本。 |
speech_noise_threshold | float | 否 | 用於區分語音與噪音的閾值,用於調整語音活動偵測(VAD)的靈敏度。 取值範圍:[-1.0, 1.0]。 取值說明:
此為進階設定參數,調整後可能顯著影響辨識效果。建議:
|
使用 recognize 建立辨識會話時,透過 input 傳入上下文。
| 參數 | 類型 | 是否必填 | 描述 |
|---|---|---|---|
input | dict | 否 | 輸入物件,用於傳入對話上下文。上下文有助於辨識,並可提升特定領域詞彙的辨識準確率。詳細用法請參閱快速入門。 該 dict 必須包含
重要上下文訊息( 重要提供上下文時, 說明此欄位於 SDK 1.25.23 引入,並包含於 2.0.1 及之後版本。 |
API 參考
Qwen-Audio-ASR-Message
關鍵 API
核心資源 (client.audio.asr)
即時語音辨識能力掛載於 client.audio.asr 資源上:recognize 建立雙向串流辨識工作階段(Recognition),recognize_file 則對本機檔案執行一次性辨識。
| 成員方法 | 方法簽章 | 描述 |
|---|---|---|
recognize | | 建立雙向串流辨識工作階段;進入 傳送音訊與消費事件必須並行執行(與 |
recognize_file | | 基於本機檔案的非串流呼叫:自動分塊傳送音訊並驅動任務直至完成,逐一產生伺服器端事件。此方法需要待辨識檔案的讀取權限。 |
start | | 啟動語音辨識:建立連線、傳送任務並等待 |
send_audio_frame | | 推送音訊。每次推送的音訊區塊不宜過大或過小;建議每個區塊的音訊時長約 100ms,大小介於 1KB 至 16KB 之間。 辨識結果透過事件迭代 ( |
stop | | 停止語音辨識:僅通知伺服器輸入已結束;接收執行緒必須繼續消費 events(),直到 task-finished 事件為止。 |
events / results | | 迭代伺服器端事件: |
close | | 關閉辨識工作階段。離開 |
request_id / first_package_delay / last_package_delay / last_response | | 取得 request_id、首包延遲(從傳送第一個音訊封包到收到第一個辨識結果之間的延遲)與末包延遲(從傳送 |
更新對話上下文
在辨識任務執行期間呼叫 update_context 更新對話上下文,以輔助後續音訊的辨識。此方法需要 DashScope Python SDK 2.0.1 或更新版本。
def update_context(self, context: dict)
- 何時呼叫:進入
with上下文(會自動呼叫start)開始串流辨識之後、呼叫stop之前。 - 參數:
context是一個字典;傳入continue-task事件的payload.input物件,其中包含context欄位。不要再用payload或input額外包裹。 - 範圍與參數限制:參見 continue-task。
以下範例重複使用已啟動的 recognition 實例。
payload_input = {
"context": [
{
"role": "user",
"content": [{"type": "input_text", "text": "你好啊"}]
},
{
"role": "assistant",
"content": [{"type": "text", "text": "你好啊,我是通义千问,有什么可以帮助你的?"}]
}
]
}
recognition.update_context(context=payload_input)
事件迭代 (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 | 在伺服器完成全部辨識後由 |
回應結果
辨識結果(RecognitionResult)
RecognitionResult 表示迭代 session 的 results() 時產生的辨識結果幀(雙向串流呼叫與非串流呼叫均可使用;events() 產生的是原始事件 dict,若需要此型別化檢視請改用 results())。
| 成員方法 | 方法簽章 | 描述 |
|---|---|---|
get_sentence | | 取得目前已辨識的句子及其時間戳記資訊。此方法回傳 Dict[str, Any](句子資訊)。 詳情請參閱句子資訊(Sentence)。 |
request_id | | 與目前事件對應之請求的 request_id。 |
is_sentence_end | | 判斷目前句子是否已結束。此方法檢查 get_sentence() 回傳的單句資訊中 end_time 欄位是否為 None——當 end_time 不為 None 時,句子已結束。 |
句子資訊(Sentence)
Sentence 類別的成員如下:
| 參數 | 類型 | 說明 |
|---|---|---|
begin_time | int | 句子開始時間,單位為 ms。 |
end_time | int | 句子結束時間,單位為毫秒。 |
text | str | 辨識出的文字。 |
words | 字詞時間戳記資訊 (Word)清單集合 | 字詞時間戳記資訊。 |
字詞時間戳記資訊 (Word)
Word 類別的成員如下:
| 參數 | 類型 | 說明 |
|---|---|---|
begin_time | int | 字詞開始時間,單位為毫秒。 |
end_time | int | 字詞結束時間,單位為毫秒。 |
text | str | 字詞。 |
punctuation | str | 標點符號。 |
错误码
如遇报错问题,请参见错误码进行排查。
若问题仍未解决,可加入语音 SDK 示例仓库中列出的开发者群反馈问题,并提供Request ID,以便进一步排查问题。