Prerequisites
- You have activated the service and obtained and configured an API Key. Configure the API Key in environment variables instead of hard-coding it in your code, to prevent security risks caused by code leaks.
- Install the latest DashScope SDK.
QuickStart
Replace {WorkspaceId} with your workspace ID and {YOUR_AUDIO_FILE} with the path to a local 16 kHz WAV file. The example prints the transcription in the terminal.
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'])