前提条件
- 已开通服务并获取与配置 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
# 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'])