azure-ai-voicelive-ts

microsoft/skills

Azure AI Voice Live SDK для JavaScript/TypeScript: голосовые ИИ-приложения с WebSocket.

Звёзды3 219
Авторmicrosoft
Установок1

Установка

SKILL.md

@azure/ai-voicelive (JavaScript/TypeScript)

SDK для голосового ИИ в реальном времени для создания двунаправленных голосовых ассистентов с Azure AI в Node.js и браузерных средах.

Установка

npm install @azure/ai-voicelive @azure/identity
# TypeScript users
npm install @types/node

Текущая версия: 1.0.0-beta.3

Поддерживаемые среды:

  • LTS-версии Node.js (20+)
  • Современные браузеры (Chrome, Firefox, Safari, Edge)

Переменные среды

AZURE_VOICELIVE_ENDPOINT=https://<resource>.cognitiveservices.azure.com
# Optional: API key if not using Entra ID
AZURE_VOICELIVE_API_KEY=<your-api-key>
# Optional: Logging
AZURE_LOG_LEVEL=info
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production

Аутентификация

Microsoft Entra Token Credential (рекомендуется)

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

// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
const credential = new DefaultAzureCredential({requiredEnvVars: ["AZURE_TOKEN_CREDENTIALS"]});
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest#credential-classes
// const credential = new ManagedIdentityCredential();
const endpoint = "https://your-resource.cognitiveservices.azure.com";

const client = new VoiceLiveClient(endpoint, credential);

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);

Иерархия клиентов

VoiceLiveClient
└── VoiceLiveSession (WebSocket connection)
    ├── updateSession()      → Configure session options
    ├── subscribe()          → Event handlers (Azure SDK pattern)
    ├── sendAudio()          → Stream audio input
    ├── addConversationItem() → Add messages/function outputs
    └── sendEvent()          → Send raw protocol events

Быстрый старт

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

const credential = new DefaultAzureCredential({requiredEnvVars: ["AZURE_TOKEN_CREDENTIALS"]});
const endpoint = process.env.AZURE_VOICELIVE_ENDPOINT!;

// Create client and start session
const client = new VoiceLiveClient(endpoint, credential);
const session = await client.startSession("gpt-4o-mini-realtime-preview");

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

// Subscribe to events
const subscription = session.subscribe({
  onResponseAudioDelta: async (event, context) => {
    // Handle streaming audio output
    const audioData = event.delta;
    playAudioChunk(audioData);
  },
  onResponseTextDelta: async (event, context) => {
    // Handle streaming text
    process.stdout.write(event.delta);
  },
  onInputAudioTranscriptionCompleted: async (event, context) => {
    console.log("User said:", event.transcript);
  },
});

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

Конфигурация сессии

await session.updateSession({
  // Modalities
  modalities: ["audio", "text"],
  
  // System instructions
  instructions: "You are a customer service representative.",
  
  // Voice selection
  voice: {
    type: "azure-standard",  // or "azure-custom", "openai"
    name: "en-US-AvaNeural",
  },
  
  // Turn detection (VAD)
  turnDetection: {
    type: "server_vad",      // or "azure_semantic_vad"
    threshold: 0.5,
    prefixPaddingMs: 300,
    silenceDurationMs: 500,
  },
  
  // Audio formats
  inputAudioFormat: "pcm16",
  outputAudioFormat: "pcm16",
  
  // Tools (function calling)
  tools: [
    {
      type: "function",
      name: "get_weather",
      description: "Get current weather",
      parameters: {
        type: "object",
        properties: {
          location: { type: "string" }
        },
        required: ["location"]
      }
    }
  ],
  toolChoice: "auto",
});

Обработка событий (шаблон Azure SDK)

SDK использует шаблон обработки событий на основе подписок:

const subscription = session.subscribe({
  // Connection lifecycle
  onConnected: async (args, context) => {
    console.log("Connected:", args.connectionId);
  },
  onDisconnected: async (args, context) => {
    console.log("Disconnected:", args.code, args.reason);
  },
  onError: async (args, context) => {
    console.error("Error:", args.error.message);
  },
  
  // Session events
  onSessionCreated: async (event, context) => {
    console.log("Session created:", context.sessionId);
  },
  onSessionUpdated: async (event, context) => {
    console.log("Session updated");
  },
  
  // Audio input events (VAD)
  onInputAudioBufferSpeechStarted: async (event, context) => {
    console.log("Speech started at:", event.audioStartMs);
  },
  onInputAudioBufferSpeechStopped: async (event, context) => {
    console.log("Speech stopped at:", event.audioEndMs);
  },
  
  // Transcription events
  onConversationItemInputAudioTranscriptionCompleted: async (event, context) => {
    console.log("User said:", event.transcript);
  },
  onConversationItemInputAudioTranscriptionDelta: async (event, context) => {
    process.stdout.write(event.delta);
  },
  
  // Response events
  onResponseCreated: async (event, context) => {
    console.log("Response started");
  },
  onResponseDone: async (event, context) => {
    console.log("Response complete");
  },
  
  // Streaming text
  onResponseTextDelta: async (event, context) => {
    process.stdout.write(event.delta);
  },
  onResponseTextDone: async (event, context) => {
    console.log("\n--- Text complete ---");
  },
  
  // Streaming audio
  onResponseAudioDelta: async (event, context) => {
    const audioData = event.delta;
    playAudioChunk(audioData);
  },
  onResponseAudioDone: async (event, context) => {
    console.log("Audio complete");
  },
  
  // Audio transcript (what assistant said)
  onResponseAudioTranscriptDelta: async (event, context) => {
    process.stdout.write(event.delta);
  },
  
  // Function calling
  onResponseFunctionCallArgumentsDone: async (event, context) => {
    if (event.name === "get_weather") {
      const args = JSON.parse(event.arguments);
      const result = await getWeather(args.location);
      
      await session.addConversationItem({
        type: "function_call_output",
        callId: event.callId,
        output: JSON.stringify(result),
      });
      
      await session.sendEvent({ type: "response.create" });
    }
  },
  
  // Catch-all for debugging
  onServerEvent: async (event, context) => {
    console.log("Event:", event.type);
  },
});

// Clean up when done
await subscription.close();

Вызов функций

// Define tools in session config
await session.updateSession({
  modalities: ["audio", "text"],
  instructions: "Help users with weather information.",
  tools: [
    {
      type: "function",
      name: "get_weather",
      description: "Get current weather for a location",
      parameters: {
        type: "object",
        properties: {
          location: {
            type: "string",
            description: "City and state or country",
          },
        },
        required: ["location"],
      },
    },
  ],
  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 fetchWeather(args.location);
      
      // Send function result
      await session.addConversationItem({
        type: "function_call_output",
        callId: event.callId,
        output: JSON.stringify(weatherData),
      });
      
      // Trigger response generation
      await session.sendEvent({ type: "response.create" });
    }
  },
});

Параметры голоса

Тип голосаКонфигурацияПример
Azure Standard{ type: "azure-standard", name: "..." }"en-US-AvaNeural"
Azure Custom{ type: "azure-custom", name: "...", endpointId: "..." }Пользовательская конечная точка голоса
Azure Personal{ type: "azure-personal", speakerProfileId: "..." }Персональный клон голоса
OpenAI{ type: "openai", name: "..." }"alloy", "echo", "shimmer"

Поддерживаемые модели

МодельОписаниеСценарий использования
gpt-4o-realtime-previewGPT-4o с аудио в реальном времениВысококачественный диалоговый ИИ
gpt-4o-mini-realtime-previewОблегчённая GPT-4oБыстрые, эффективные взаимодействия
phi4-mm-realtimeМультимодальная PhiЭкономичные приложения

Параметры определения реплик

// Server VAD (default)
turnDetection: {
  type: "server_vad",
  threshold: 0.5,
  prefixPaddingMs: 300,
  silenceDurationMs: 500,
}

// Azure Semantic VAD (smarter detection)
turnDetection: {
  type: "azure_semantic_vad",
}

// Azure Semantic VAD (English optimized)
turnDetection: {
  type: "azure_semantic_vad_en",
}

// Azure Semantic VAD (Multilingual)
turnDetection: {
  type: "azure_semantic_vad_multilingual",
}

Аудиоформаты

ФорматЧастота дискретизацииСценарий использования
pcm1624kHzПо умолчанию, высокое качество
pcm16-8000hz8kHzТелефония
pcm16-16000hz16kHzГолосовые ассистенты
g711_ulaw8kHzТелефония (США)
g711_alaw8kHzТелефония (ЕС)

Справочник по типам

ТипНазначение
VoiceLiveClientОсновной клиент для создания сессий
VoiceLiveSessionАктивная сессия WebSocket
VoiceLiveSessionHandlersИнтерфейс обработчика событий
VoiceLiveSubscriptionАктивная подписка на события
ConnectionContextКонтекст для событий подключения
SessionContextКонтекст для событий сессии
ServerEventUnionОбъединение всех серверных событий

Обработка ошибок

import {
  VoiceLiveError,
  VoiceLiveConnectionError,
  VoiceLiveAuthenticationError,
  VoiceLiveProtocolError,
} from "@azure/ai-voicelive";

const subscription = session.subscribe({
  onError: async (args, context) => {
    const { error } = args;
    
    if (error instanceof VoiceLiveConnectionError) {
      console.error("Connection error:", error.message);
    } else if (error instanceof VoiceLiveAuthenticationError) {
      console.error("Auth error:", error.message);
    } else if (error instanceof VoiceLiveProtocolError) {
      console.error("Protocol error:", error.message);
    }
  },
  
  onServerError: async (event, context) => {
    console.error("Server error:", event.error?.message);
  },
});

Логирование

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

// Enable verbose logging
setLogLevel("info");

// Or via environment variable
// AZURE_LOG_LEVEL=info

Использование в браузере

// Browser requires bundler (Vite, webpack, etc.)
import { VoiceLiveClient } from "@azure/ai-voicelive";
import { InteractiveBrowserCredential } from "@azure/identity";

// Use browser-compatible credential
const credential = new InteractiveBrowserCredential({
  clientId: "your-client-id",
  tenantId: "your-tenant-id",
});

const client = new VoiceLiveClient(endpoint, credential);

// Request microphone access
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const audioContext = new AudioContext({ sampleRate: 24000 });

// Process audio and send to session
// ... (see samples for full implementation)

Рекомендации

  1. Используйте DefaultAzureCredential для локальной разработки; используйте ManagedIdentityCredential or WorkloadIdentityCredential для продакшена — Никогда не хардкодьте API-ключи
  2. Задавайте обе модальности — Включайте ["text", "audio"] для голосовых ассистентов
  3. Используйте Azure Semantic VAD — Лучшее определение реплик, чем базовый серверный VAD
  4. Обрабатывайте все типы ошибок — Ошибки подключения, аутентификации и протокола
  5. Очищайте подписки — Вызывайте subscription.close() по завершении
  6. Используйте подходящий аудиоформат — PCM16 при 24kHz для лучшего качества

Ссылки

РесурсURL
Пакет npmhttps://www.npmjs.com/package/@azure/ai-voicelive
Исходный код на GitHubhttps://github.com/Azure/azure-sdk-for-js/tree/main/sdk/ai/ai-voicelive
Примерыhttps://github.com/Azure/azure-sdk-for-js/tree/main/sdk/ai/ai-voicelive/samples
Справочник по APIhttps://learn.microsoft.com/javascript/api/@azure/ai-voicelive

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: azure-ai-voicelive-ts](https://darkplay.ru/ai/skills/microsoft-skills-azure-ai-voicelive-ts)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

hyperframesheygen-com · Все навыки HyperFrames в одном статическом наборе. В большинстве случаев лучше…
27 комп.
agentic-bundle-azure-ai-cloudsickn33 · Установите набор редакционных навыков "Azure AI & Cloud" для Claude Code.
49 917 ★
airwallex-agentosanthropics · Глобальная финансовая инфраструктура Airwallex в Claude. Управляйте действиями по счёту…
100 комп.
azureanthropics · Превращает Claude в эксперта по Azure. Плагин объединяет Azure MCP-сервер и…
100 комп.
azure-cosmos-db-assistantanthropics · Экспертный помощник по Azure Cosmos DB — моделирование данных, оптимизация запросов…
100 комп.
hyperframesanthropics · HyperFrames от HeyGen. Пишите HTML — получайте видео. Композиции, анимации GSAP и…
100 комп.
microsoft-docsanthropics · Доступ к официальной документации Microsoft, справочникам API и примерам кода для Azure…
100 комп.
oracle-ai-data-platform-workbench-spark-connectorsanthropics · Коннекторы Spark для Oracle AI Data Platform Workbench в Claude Code. 18…
100 комп.
twilio-developer-kitanthropics · Twilio Skills дают AI-агентам для кодинга процедурные знания: какие API использовать, в…
100 комп.
cloud-infrastructurewshobson · Проектирование облачной архитектуры для AWS/Azure/GCP/OCI, настройка кластеров…
495 комп.

Лучшие ИИ-инструменты для музыки, голоса и озвучки

Музыка, голос и озвучка

Подборка нейросетей для генерации музыки, голоса и озвучки. Сервисы, которые помогают создавать треки, синтезировать речь и чистить аудио без студии и дикторов. Подходит для видеом

TimbricaTimbrica
По запросу
5.0
BigspeakBigspeak
По запросу
5.0
WavToolWavtool
По запросу
5.0
LoquoraLoquora
Есть бесплатный тариф
4.9
WunjoWunjo
Есть бесплатный тариф
4.9
NexaraNexara
Есть бесплатный тариф
4.9
pitch coachApple
По запросу
4.9
audio-transcription.ruAudio-transcription
Есть бесплатный тариф
4.9
SoundfulSoundful
По запросу
4.9
TutDub
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8