使用 Azure AI Voice Live SDK 构建实时语音 AI 应用。适用于需与 Azure AI 进行实时双向音频通信的 Python 应用,涵盖语音助手、实时语音翻译及 AI 音频流等场景。支持服务端 VAD、轮流对话、函数调用、MCP 工具、虚拟形象集成及转录功能。
Azure AI Voice Live SDK. 构建双向WebSocket通信的实时语音AI应用程序. . 环境变量. 认证.
功能概述
Azure AI Voice Live SDK. 构建双向WebSocket通信的实时语音AI应用程序. . 环境变量. 认证.是一项面向实际任务的技能,主要用于Default AzureCreditive(首选) : 1.。它将相关步骤、工具调用和结果整理方式集中到统一流程中,帮助使用者更快完成目标并减少重复操作。
核心要点
- 使用时应结合输入条件选择合适的执行方式,核对必要参数、依赖环境与输出内容,并按原始要求处理异常情况。
- 该技能适合需要稳定复用相关能力的场景,可作为自动化工作流的一部分,也便于后续检查、调整和扩展。
- 从功能定位来看,该技能强调把分散的操作要求整理成清晰、可复用的处理流程,使用户能够围绕既定目标快速准备输入、选择执行方式并获得结构化结果。
使用与执行
实际使用前应先确认任务范围、数据来源、运行环境、必要权限和关键参数,再依据技能说明逐步执行;若输入条件不完整,应先补齐信息或采用保守配置,避免因错误假设导致结果偏离需求。
结果检查与注意事项
执行过程中需要关注工具调用是否成功、接口或依赖是否可用、输出格式是否符合预期,并对异常提示、缺失字段和边界情况进行处理;涉及批量任务时,还应保存进度,避免中断后重复操作。
Azure AI Voice Live SDK
使用双向 WebSocket 通信构建实时语音 AI 应用程序。
安装
pip install azure-ai-voicelive aiohttp azure-identity
环境变量
AZURE_COGNITIVE_SERVICES_ENDPOINT=https://.api.cognitive.microsoft.com # 使用 API 密钥认证(不建议用于生产环境) AZURE_COGNITIVE_SERVICES_KEY=
认证
DefaultAzureCredential(推荐):
from azure.ai.voicelive.aio import connect
from azure.identity.aio import DefaultAzureCredential
async with connect(
endpoint=os.environ["AZURE_COGNITIVE_SERVICES_ENDPOINT"],
credential=DefaultAzureCredential(),
model="gpt-4o-realtime-preview",
credential_scopes=["https://cognitiveservices.azure.com/.default"]
) as conn:
...
API 密钥:
from azure.ai.voicelive.aio import connect
from azure.core.credentials import AzureKeyCredential
async with connect(
endpoint=os.environ["AZURE_COGNITIVE_SERVICES_ENDPOINT"],
credential=AzureKeyCredential(os.environ["AZURE_COGNITIVE_SERVICES_KEY"]),
model="gpt-4o-realtime-preview"
) as conn:
...
快速开始
import asyncio
import os
from azure.ai.voicelive.aio import connect
from azure.identity.aio import DefaultAzureCredential
async def main():
async with connect(
endpoint=os.environ["AZURE_COGNITIVE_SERVICES_ENDPOINT"],
credential=DefaultAzureCredential(),
model="gpt-4o-realtime-preview",
credential_scopes=["https://cognitiveservices.azure.com/.default"]
) as conn:
# 更新会话配置
await conn.session.update(session={
"instructions": "You are a helpful assistant.",
"modalities": ["text", "audio"],
"voice": "alloy"
})
# 监听事件
async for event in conn:
print(f"Event: {event.type}")
if event.type == "response.audio_transcript.done":
print(f"Transcript: {event.transcript}")
elif event.type == "response.done":
break
asyncio.run(main())
核心架构
连接资源
VoiceLiveConnection 暴露以下资源:
| 资源 | 用途 | 关键方法 |
|---|---|---|
conn.session |
会话配置 | update(session=...) |
conn.response |
模型响应 | create(), cancel() |
conn.input_audio_buffer |
音频输入 | append(), commit(), clear() |
conn.output_audio_buffer |
音频输出 | clear() |
conn.conversation |
对话状态 | item.create(), item.delete(), item.truncate() |
conn.transcription_session |
语音转录配置 | update(session=...) |
会话配置
from azure.ai.voicelive.models import RequestSession, FunctionTool
await conn.session.update(session=RequestSession(
instructions="You are a helpful voice assistant.",
modalities=["text", "audio"],
voice="alloy", # 或 "echo", "shimmer", "sage" 等
input_audio_format="pcm16",
output_audio_format="pcm16",
turn_detection={
"type": "server_vad",
"threshold": 0.5,
"prefix_padding_ms": 300,
"silence_duration_ms": 500
},
tools=[
FunctionTool(
type="function",
name="get_weather",
description="Get current weather",
parameters={
"type": "object",
"properties": {
"location": {"type": "string"}
},
"required": ["location"]
}
)
]
))
音频流式传输
发送音频(Base64 编码的 PCM16)
import base64 # 读取音频片段(16 位 PCM,24kHz 单声道) audio_chunk = await read_audio_from_microphone() b64_audio = base64.b64encode(audio_chunk).decode() await conn.input_audio_buffer.append(audio=b64_audio)
接收音频
async for event in conn:
if event.type == "response.audio.delta":
audio_bytes = base64.b64decode(event.delta)
await play_audio(audio_bytes)
elif event.type == "response.audio.done":
print("Audio complete")
事件处理
async for event in conn:
match event.type:
# 会话事件
case "session.created":
print(f"Session: {event.session}")
case "session.updated":
print("Session updated")
# 音频输入事件
case "input_audio_buffer.speech_started":
print(f"Speech started at {event.audio_start_ms}ms")
case "input_audio_buffer.speech_stopped":
print(f"Speech stopped at {event.audio_end_ms}ms")
# 转录事件
case "conversation.item.input_audio_transcription.completed":
print(f"User said: {event.transcript}")
case "conversation.item.input_audio_transcription.delta":
print(f"Partial: {event.delta}")
# 响应事件
case "response.created":
print(f"Response started: {event.response.id}")
case "response.audio_transcript.delta":
print(event.delta, end="", flush=True)
case "response.audio.delta":
audio = base64.b64decode(event.delta)
case "response.done":
print(f"Response complete: {event.response.status}")
# 函数调用
case "response.function_call_arguments.done":
result = handle_function(event.name, event.arguments)
await conn.conversation.item.create(item={
"type": "function_call_output",
"call_id": event.call_id,
"output": json.dumps(result)
})
await conn.response.create()
# 错误
case "error":
print(f"Error: {event.error.message}")
常见模式
手动轮转模式(禁用 VAD)
await conn.session.update(session={"turn_detection": None})
# 手动控制轮转
await conn.input_audio_buffer.append(audio=b64_audio)
await conn.input_audio_buffer.commit() # 用户轮转结束
await conn.response.create() # 触发响应
中断处理
async for event in conn:
if event.type == "input_audio_buffer.speech_started":
# 用户中断 —— 取消当前响应
await conn.response.cancel()
await conn.output_audio_buffer.clear()
对话历史
# 添加系统消息
await conn.conversation.item.create(item={
"type": "message",
"role": "system",
"content": [{"type": "input_text", "text": "Be concise."}]
})
# 添加用户消息
await conn.conversation.item.create(item={
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": "Hello!"}]
})
await conn.response.create()
语音选项
| 语音 | 描述 |
|---|---|
alloy |
中性、均衡 |
echo |
温暖、自然对话风格 |
shimmer |
清晰、专业 |
sage |
沉稳、权威 |
coral |
友好、积极向上 |
ash |
低沉、稳健 |
ballad |
富有表现力 |
verse |
适合讲故事 |
Azure 语音:使用 AzureStandardVoice、AzureCustomVoice 或 AzurePersonalVoice 模型。
音频格式
| 格式 | 采样率 | 适用场景 |
|---|---|---|
pcm16 |
24kHz | 默认,高音质 |
pcm16-8000hz |
8kHz | 电话通信 |
pcm16-16000hz |
16kHz | 语音助手 |
g711_ulaw |
8kHz | 电话通信(美国) |
g711_alaw |
8kHz | 电话通信(欧洲) |
轮转检测选项
# 服务端 VAD(默认)
{"type": "server_vad", "threshold": 0.5, "silence_duration_ms": 500}
# Azure 语义 VAD(更智能的检测)
{"type": "azure_semantic_vad"}
{"type": "azure_semantic_vad_en"} # 英语优化版
{"type": "azure_semantic_vad_multilingual"}
错误处理
from azure.ai.voicelive.aio import ConnectionError, ConnectionClosed
try:
async with connect(...) as conn:
async for event in conn:
if event.type == "error":
print(f"API Error: {event.error.code} - {event.error.message}")
except ConnectionClosed as e:
print(f"Connection closed: {e.code} - {e.reason}")
except ConnectionError as e:
print(f"Connection error: {e}")
参考文档
- 详细 API 参考:参见 references/api-reference.md
- 完整示例:参见 references/examples.md
- 所有模型与类型定义:参见 references/models.md
热门AI工具
相关专题
DBeaver数据导入专题,整理Excel、CSV、SQL、TXT等常见文件的数据导入方法,涵盖目标数据库选择、数据表创建、字段映射、数据类型设置及导入参数配置等操作,帮助用户将本地文件中的数据写入数据库,并了解批量导入、重复数据处理和导入失败等常见问题的解决方法。
0
2026.11.05
DBeaver安全防护专题,围绕数据库连接安全、账号密码保护和访问权限管理展开,整理SSL/TLS加密连接、SSH隧道、数据库凭据保存及证书验证等配置方法,同时介绍敏感信息保护、远程连接风险和高权限账号使用等注意事项,帮助用户提高数据库日常管理的安全性。
0
2026.11.05
本专题聚焦DBeaver数据库连接配置与管理,覆盖从新建连接、选择数据库类型到填写连接参数和验证连接的完整流程。针对MySQL、PostgreSQL、SQL Server等常见数据库,整理相应的连接设置方法,并提供驱动缺失、认证失败和连接异常等问题的排查方向。
0
2026.11.04
本专题围绕XORM框架的结构体映射展开,说明表名与字段的命名策略、xorm标签常用属性、主键自增与时间字段自动填充,并演示Sync2自动建表、增量字段升级、索引声明与反向生成结构体的完整流程。
0
2026.11.04
本专题聚焦XORM框架的配置与连接环节,拆解MySQL、PostgreSQL、SQLite、SQL Server的DSN写法与驱动选择,讲清连接池参数、多数据源拆分、读写分离与超时重连的处理方式,并补充容器与兼容数据库的适配经验。
0
2026.11.04
本专题聚焦XORM框架的配置与连接环节,拆解MySQL、PostgreSQL、SQLite、SQL Server的DSN写法与驱动选择,讲清连接池参数、多数据源拆分、读写分离与超时重连的处理方式,并补充容器与兼容数据库的适配经验。
0
2026.11.04
本专题聚焦XORM框架的配置与连接环节,拆解MySQL、PostgreSQL、SQLite、SQL Server的DSN写法与驱动选择,讲清连接池参数、多数据源拆分、读写分离与超时重连的处理方式,并补充容器与兼容数据库的适配经验。
0
2026.11.04
本专题梳理XORM框架的入门路径,从框架定位、依赖安装、连接数据库到跑通第一个增删改查示例,讲清Engine初始化、日志开启与项目目录规划,并对比GORM等同类ORM的差异,帮助Go开发者建立整体认知。
0
2026.11.04
本专题聚焦Docker Desktop容器端口映射与访问配置,整理从创建容器、设置端口绑定到验证本地服务访问的操作流程。针对端口被占用、映射配置错误、容器服务无法访问等情况,也提供相应的检查方向,方便用户完成端口配置。
0
2026.11.03
热门下载
相关下载
精品课程
共6课时 | 12.1万人学习
共79课时 | 161.7万人学习
共6课时 | 54.7万人学习
最新文章