前提條件
- 已開通服務並擷取與配置 API Key。請配置API Key到環境變數,而非寫入程式碼在代碼中,防範因代碼泄露導致的安全風險。
- 安裝最新版DashScope SDK。
快速開始
將範例中的 {WorkspaceId} 換成實際的工作空間 ID,將 {YOUR_AUDIO_FILE} 換成本機 16 kHz WAV 檔案的路徑。執行後,終端機會顯示辨識結果。
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
{WorkspaceId} 換成實際的工作空間 ID,將 {YOUR_AUDIO_FILE} 換成本機 16 kHz WAV 檔案的路徑。執行後,終端機會顯示辨識結果。
import os
import dashscope
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
client = dashscope.Client(
api_key=os.environ.get('DASHSCOPE_API_KEY'),
# 以下為新加坡(ap-southeast-1)地區的配置。調用時請將"{WorkspaceId}"替換為真實的業務空間ID,各地區的配置不同。
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
# 識別本地語音檔案:recognize_file自動分塊發送音頻並驅動到任務結束
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'])