你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

Azure VoiceLive client library for JavaScript - version 1.0.0-beta.1

Azure VoiceLive 是一项托管服务,能够为语音代理实现低延迟、高质量的语音对语音交互。 该服务将语音识别、生成式人工智能和文本转语音功能整合到一个统一界面,提供端到端解决方案,打造无缝的语音驱动体验。

使用客户端库可以:

  • 创建实时语音助手和对话代理
  • 构建延迟极低的语音转语音应用
  • 集成先进的对话功能,如噪音抑制和回声消除
  • 利用多种AI模型(GPT-4o、GPT-4o-mini、Phi)来应对不同的应用场景
  • 实现函数调用和工具集成以实现动态响应
  • 创建带有视觉组件的头像语音交互

注意:该软件包支持浏览器和 Node.js 环境。 WebSocket连接用于实时通信。

入门指南

当前支持的环境

先决条件

安装软件包

使用 npm 安装 Azure VoiceLive 客户端库:

npm install @azure/ai-voicelive

安装身份库

VoiceLive 客户端通过 Azure 身份库进行认证。 也安装它:

npm install @azure/identity

配置TypeScript

TypeScript 用户需要安装 Node 类型定义:

npm install @types/node

你还需要在 tsconfig.json中启用 compilerOptions.allowSyntheticDefaultImports 。 注意,如果你启用 compilerOptions.esModuleInterop了,默认 allowSyntheticDefaultImports 是启用的。

JavaScript 捆绑包

若要在浏览器中使用此客户端库,首先需要使用捆绑程序。 有关如何执行此作的详细信息,请参阅我们的 捆绑文档

重要概念

VoiceLive客户端

建立与Azure VoiceLive服务连接的主要接口。 使用该客户端进行身份验证并创建会话,实现实时语音交互。

语音直播会话

表示用于实时语音通信的活跃WebSocket连接。 这门课处理双向通信,允许你实时发送音频输入和接收音频输出、文本转录及其他事件。

会话配置

该服务利用会话配置控制语音交互的各个方面:

  • 转向检测:配置服务如何检测用户何时开始和停止发言
  • 音频处理:启用降噪和回声消除
  • 语音选择:可选择标准 Azure 语音、高清语音或自定义语音
  • 模型选择:选择最适合您需求的AI模型(GPT-4o、GPT-4o-mini、Phi变体)

型号与功能

VoiceLive API 支持多个具有不同功能的 AI 模型:

型号 Description 用例
gpt-4o-realtime-preview 具备实时音频处理功能的GPT-4o 高质量的对话式人工智能
gpt-4o-mini-realtime-preview 轻量级GPT-4o变体 快速高效的互动
phi4-mm-realtime 支持多模态的Phi模型 经济高效的语音应用

对话功能增强

VoiceLive API 提供了 Azure 专用的增强功能:

  • Azure 语义 VAD:高级语音活动检测,去除填充词
  • 噪声抑制:减少环境背景噪音
  • 回声消除:去除模特声音中的回声
  • 回合结束检测:允许自然暂停且不会过早中断

使用 Azure Active Directory 认证

VoiceLive 服务依赖 Azure Active Directory 来认证其 API 请求。 @azure/identity 包提供了应用程序可用于执行此操作的各种凭据类型。 @azure/identity 自述文件提供了更多详细信息和示例来帮助你入门。

要与 Azure VoiceLive 服务交互,你需要创建一个类实例 VoiceLiveClient一个服务端点 和一个凭据对象。 本文档中展示的示例使用名为 DefaultAzureCredential的凭证对象,适用于大多数场景,包括本地开发和生产环境。 我们建议在生产环境中使用 托管身份 进行认证。

您可以在 Azure 身份文档中找到关于不同身份验证方式及其对应凭证类型的更多信息。

这里有一个简短的例子。 首先,导入 DefaultAzureCredentialVoiceLiveClient

import { DefaultAzureCredential } from "@azure/identity";
import { VoiceLiveClient } from "@azure/ai-voicelive";

const credential = new DefaultAzureCredential();

// Build the URL to reach your AI Foundry resource
const endpoint = "https://your-resource.cognitiveservices.azure.com";

// Create the VoiceLive client
const client = new VoiceLiveClient(endpoint, credential);

使用API密钥进行认证

在开发场景中,你也可以使用 API 密钥进行认证:

import { AzureKeyCredential } from "@azure/core-auth";
import { VoiceLiveClient } from "@azure/ai-voicelive";

const endpoint = "https://your-resource.cognitiveservices.azure.com";
const credential = new AzureKeyCredential("your-api-key");

const client = new VoiceLiveClient(endpoint, credential);

例子

以下章节提供了代码摘要,涵盖使用 Azure VoiceLive 的一些常见任务。 这里涵盖的情景包括:

创建基础语音助手

这个例子展示了如何创建一个能够处理语音对语音交互的简单语音助手:

import { DefaultAzureCredential } from "@azure/identity";
import { VoiceLiveClient } from "@azure/ai-voicelive";

const credential = new DefaultAzureCredential();
const endpoint = "https://your-resource.cognitiveservices.azure.com";

// Create the client
const client = new VoiceLiveClient(endpoint, credential);

// Create and connect a session
const session = await client.startSession("gpt-4o-mini-realtime-preview");

// Configure session for voice conversation
await session.updateSession({
  modalities: ["text", "audio"],
  instructions: "You are a helpful AI assistant. Respond naturally and conversationally.",
  voice: {
    type: "azure-standard",
    name: "en-US-AvaNeural",
  },
  turnDetection: {
    type: "server_vad",
    threshold: 0.5,
    prefixPaddingMs: 300,
    silenceDurationMs: 500,
  },
  inputAudioFormat: "pcm16",
  outputAudioFormat: "pcm16",
});

会话选项配置

你可以自定义语音互动的各个方面:

import { DefaultAzureCredential } from "@azure/identity";
import { VoiceLiveClient } from "@azure/ai-voicelive";

const credential = new DefaultAzureCredential();
const endpoint = "https://your-resource.cognitiveservices.azure.com";
const client = new VoiceLiveClient(endpoint, credential);
const session = await client.startSession("gpt-4o-realtime-preview");

// Advanced session configuration
await session.updateSession({
  modalities: ["audio", "text"],
  instructions: "You are a customer service representative. Be helpful and professional.",
  voice: {
    type: "azure-custom",
    name: "your-custom-voice-name",
    endpointId: "your-custom-voice-endpoint",
  },
  turnDetection: {
    type: "server_vad",
    threshold: 0.6,
    prefixPaddingMs: 200,
    silenceDurationMs: 300,
  },
  inputAudioFormat: "pcm16",
  outputAudioFormat: "pcm16",
});

处理实时事件

VoiceLive 客户端为实时交互提供事件驱动的通信:

import { DefaultAzureCredential } from "@azure/identity";
import { VoiceLiveClient } from "@azure/ai-voicelive";

const credential = new DefaultAzureCredential();
const endpoint = "https://your-resource.cognitiveservices.azure.com";
const client = new VoiceLiveClient(endpoint, credential);
const session = await client.startSession("gpt-4o-mini-realtime-preview");

// Set up event handlers using subscription pattern
const subscription = session.subscribe({
  onResponseAudioDelta: async (event, context) => {
    // Handle incoming audio chunks
    const audioData = event.delta;
    // Play audio using Web Audio API or other audio system
    playAudioChunk(audioData);
  },

  onResponseTextDelta: async (event, context) => {
    // Handle incoming text deltas
    console.log("Assistant:", event.delta);
  },

  onInputAudioTranscriptionCompleted: async (event, context) => {
    // Handle user speech transcription
    console.log("User said:", event.transcript);
  },
});

// Send audio data from microphone
function sendAudioChunk(audioBuffer: ArrayBuffer) {
  session.sendAudio(audioBuffer);
}

实现函数调用

启用你的语音助手调用外部功能和工具:

import { DefaultAzureCredential } from "@azure/identity";
import { VoiceLiveClient } from "@azure/ai-voicelive";

const credential = new DefaultAzureCredential();
const endpoint = "https://your-resource.cognitiveservices.azure.com";
const client = new VoiceLiveClient(endpoint, credential);
const session = await client.startSession("gpt-4o-mini-realtime-preview");

// Define available functions
const tools = [
  {
    type: "function",
    name: "get_weather",
    description: "Get current weather for a location",
    parameters: {
      type: "object",
      properties: {
        location: {
          type: "string",
          description: "The city and state or country",
        },
      },
      required: ["location"],
    },
  },
];

// Configure session with tools
await session.updateSession({
  modalities: ["audio", "text"],
  instructions:
    "You can help users with weather information. Use the get_weather function when needed.",
  tools: tools,
  toolChoice: "auto",
});

// Handle function calls
const subscription = session.subscribe({
  onResponseFunctionCallArgumentsDone: async (event, context) => {
    if (event.name === "get_weather") {
      const args = JSON.parse(event.arguments);
      const weatherData = await getWeatherData(args.location);

      // Send function result back
      await session.addConversationItem({
        type: "function_call_output",
        callId: event.callId,
        output: JSON.stringify(weatherData),
      });

      // Request response generation
      await session.sendEvent({
        type: "response.create",
      });
    }
  },
});

Troubleshooting

常见错误和异常

认证错误:如果收到认证错误,请确认:

  • 您的Azure AI Foundry资源配置正确
  • 你的API密钥或凭证具备必要的权限
  • 端点URL是正确且可访问的

WebSocket连接问题:VoiceLive使用WebSocket连接。 请确保:

  • 你的网络允许WebSocket连接
  • 防火墙规则允许连接 *.cognitiveservices.azure.com
  • 浏览器策略允许使用WebSocket和麦克风访问(用于浏览器使用)

音频问题:关于音频相关问题:

  • 在浏览器中验证麦克风权限
  • 检查是否支持音频格式(PCM16、PCM24)
  • 确保播放时音频上下文设置得当

伐木业

启用日志记录可能有助于发现有关故障的有用信息。 为了查看WebSocket消息和响应的日志,将环境变量info设置为 AZURE_LOG_LEVEL 。 或者,可以通过在 setLogLevel中调用 @azure/logger 在运行时启用日志记录:

import { setLogLevel } from "@azure/logger";

setLogLevel("info");

有关如何启用日志的更详细说明,可以查看 @azure/记录器包文档

后续步骤

您可以通过以下链接找到更多代码示例:

Contributing

若要参与此库,请阅读 参与指南 ,详细了解如何生成和测试代码。