Notitie
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen u aan te melden of de directory te wijzigen.
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen de mappen te wijzigen.
Azure VoiceLive is een beheerde dienst die spraak-naar-spraakinteracties met lage latentie en hoge kwaliteit voor spraakagenten mogelijk maakt. De dienst consolideert spraakherkenning, generatieve AI en tekst-naar-spraak functionaliteiten in één uniforme interface, waarmee een end-to-end oplossing wordt geboden voor het creëren van naadloze spraakgestuurde ervaringen.
Gebruik de clientbibliotheek voor het volgende:
- Creëer realtime stemassistenten en gespreksagenten
- Bouw spraak-naar-spraak applicaties met minimale latentie
- Integreer geavanceerde conversatiefuncties zoals ruisonderdrukking en echo-onderdrukking
- Maak gebruik van meerdere AI-modellen (GPT-Realtime, GPT-Realtime-Mini, Phi) voor verschillende gebruikssituaties
- Implementeer functieaanroep en toolintegratie voor dynamische antwoorden
- Maak avatar-ondersteunde spraakinteracties met visuele componenten
Opmerking: Dit pakket ondersteunt zowel browser- als Node.js omgevingen. WebSocket-verbindingen worden gebruikt voor realtime communicatie.
Aan de slag
Momenteel ondersteunde omgevingen
- LTS-versies van Node.js
- Nieuwste versies van Safari, Chrome, Edge en Firefox
Prerequisites
- Een Azure-abonnement
- Een Azure AI Foundry-bron met toegang tot de Voice Live API
Installeer het pakket
Installeer de Azure VoiceLive-clientbibliotheek met npm:
npm install @azure/ai-voicelive
Installeer de identiteitsbibliotheek
VoiceLive-clients authenticeren met behulp van de Azure Identity Library. Installeer het ook:
npm install @azure/identity
Configureer TypeScript
TypeScript-gebruikers moeten Node-typedefinities hebben geïnstalleerd:
npm install @types/node
Je moet ook in je tsconfig.jsoninschakelen compilerOptions.allowSyntheticDefaultImports . Let op: als je het hebt ingeschakeld compilerOptions.esModuleInterop, allowSyntheticDefaultImports is het standaard ingeschakeld.
JavaScript-bundel
Als u deze clientbibliotheek in de browser wilt gebruiken, moet u eerst een bundelaar gebruiken. Raadpleeg onze bundeldocumentatie voor meer informatie over hoe u dit doet.
Belangrijke concepten
VoiceLiveClient
De primaire interface voor het tot stand brengen van verbindingen met de Azure VoiceLive-dienst. Gebruik deze client om sessies te authenticeren en te creëren voor realtime spraakinteracties.
VoiceLiveSession
Vertegenwoordigt een actieve WebSocket-verbinding voor realtime spraakcommunicatie. Deze cursus verzorgt bidirectionele communicatie, waardoor je audio-invoer en -ontvangst, teksttranscripties en andere gebeurtenissen in realtime kunt verzenden en ontvangen.
Sessieconfiguratie
De dienst gebruikt sessieconfiguratie om verschillende aspecten van spraakinteractie te beheersen:
- Beurtdetectie: Configureer hoe de dienst detecteert wanneer gebruikers beginnen en stoppen met spreken
- Audioverwerking: Schakel ruisonderdrukking en echo-onderdrukking in
- Stemselectie: Kies uit standaard Azure-stemmen, high-definition stemmen of aangepaste stemmen
- Modelkeuze: Kies het AI-model (GPT-Realtime, GPT-Realtime-Mini, Phi-varianten) dat het beste bij uw behoeften past
Modellen en mogelijkheden
De VoiceLive API ondersteunt meerdere AI-modellen met verschillende mogelijkheden:
| Model | Description | Gebruikssituatie |
|---|---|---|
gpt-realtime |
Real-time audioverwerkingsmodel | Hoogwaardige conversatie-AI |
gpt-realtime-mini |
Lichtgewicht realtime model | Snelle, efficiënte interacties |
phi4-mm-realtime |
Phi-model met multimodale ondersteuning | Kosteneffectieve spraakapplicaties |
Gespreksverbeteringen
De VoiceLive API biedt Azure-specifieke verbeteringen:
- Azure Semantic VAD: Geavanceerde spraakactiviteitsdetectie die opvulwoorden verwijdert
- Geluidsonderdrukking: Vermindert omgevingsgeluid
- Echo-onderdrukking: Verwijdert echo uit de eigen stem van het model
- End-of-Turn Detection: Maakt natuurlijke pauzes mogelijk zonder voortijdige onderbreking
Sessiemodi
VoiceLive ondersteunt twee verschillende modi voor het aanmaken van sessies:
Modelmodus (LLM als hoofdacteur)
In modelmodus is het LLM-model de primaire AI-actor. Je specificeert een modelnaam en configureert optioneel tools zoals functies of MCP-servers.
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);
// Model mode - LLM is the main actor
const session = await client.startSession("gpt-realtime");
Agent Mode (Agent als hoofdacteur)
In agentmodus is een Foundry-agent de primaire AI-actor. De configuratie van de agent (tools, instructies, temperatuur) wordt beheerd in het Azure AI Foundry-portaal, niet in sessiecode. Dit is ideaal voor:
- Spraak-ondersteunende bestaande tekstgebaseerde agenten
- Scenario's waarin agentconfiguratie centraal beheerd moet worden
- Vereenvoudigde integratie zonder runtime-configuratie
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);
// Agent mode - Foundry agent is the main actor
const session = await client.startSession({
agent: {
agentName: "my-agent",
projectName: "my-foundry-project",
},
});
Authenticatie met Azure Active Directory
De VoiceLive-service vertrouwt op Azure Active Directory om verzoeken aan zijn API's te authenticeren. Het @azure/identity-pakket biedt verschillende referentietypen die uw toepassing hiervoor kan gebruiken. De LEESMIJ voor @azure/identity biedt meer informatie en voorbeelden om u op weg te helpen.
Om met de Azure VoiceLive-service te communiceren, moet je een instantie van de VoiceLiveClient klasse, een service-endpoint en een credential-object aanmaken. De voorbeelden in dit document gebruiken een credential-object genaamd DefaultAzureCredential, dat geschikt is voor de meeste scenario's, inclusief lokale ontwikkel- en productieomgevingen. Wij raden aan om een beheerde identiteit te gebruiken voor authenticatie in productieomgevingen.
Meer informatie over verschillende authenticatiemethoden en hun bijbehorende credentialtypes vindt u in de Azure Identity-documentatie.
Hier is een snel voorbeeld. Ten eerste, importeren DefaultAzureCredential en VoiceLiveClient:
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);
Authenticatie met API-sleutel
Voor ontwikkelscenario's kun je ook authenticeren met een API-sleutel:
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);
Voorbeelden
De volgende secties bieden codefragmenten die enkele veelvoorkomende taken met Azure VoiceLive behandelen. De hier behandelde scenario's zijn:
- Een eenvoudige stemassistent maken
- Het creëren van een door agenten aangedreven stemassistent
- Sessieopties configureren
- Afhandeling van realtime gebeurtenissen
- Implementatie van functieaanroepen
Een eenvoudige stemassistent maken
Dit voorbeeld laat zien hoe je een eenvoudige spraakassistent kunt maken die spraak-naar-spraakinteracties aankan:
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-realtime-mini");
// 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,
prefixPaddingInMs: 300,
silenceDurationInMs: 500,
},
inputAudioFormat: "pcm16",
outputAudioFormat: "pcm16",
});
Het creëren van een door agenten aangedreven stemassistent
Dit voorbeeld laat zien hoe je een stemassistent kunt maken die wordt aangedreven door een Foundry-agent. In agentmodus wordt de configuratie van de agent beheerd in het Azure AI Foundry-portaal:
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 with an agent as the main actor
const session = await client.startSession({
agent: {
agentName: "your-agent-name",
projectName: "your-foundry-project",
},
});
// Subscribe to events - audio settings can still be configured
const subscription = session.subscribe({
onResponseAudioDelta: async (event, context) => {
// Handle audio from the agent
playAudioChunk(event.delta);
},
onResponseTextDelta: async (event, context) => {
console.log("Agent:", event.delta);
},
});
// Send audio data from microphone
function sendAudioChunk(audioBuffer: ArrayBuffer) {
session.sendAudio(audioBuffer);
}
Sessieopties configureren
Je kunt verschillende aspecten van de spraakinteractie aanpassen:
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-realtime");
// 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,
prefixPaddingInMs: 200,
silenceDurationInMs: 300,
},
inputAudioFormat: "pcm16",
outputAudioFormat: "pcm16",
});
Afhandeling van realtime gebeurtenissen
De VoiceLive-client biedt gebeurtenisgestuurde communicatie voor realtime interacties:
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-realtime-mini");
// 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);
},
onConversationItemInputAudioTranscriptionCompleted: 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);
}
Implementatie van functieaanroepen
Laat uw spraakassistent externe functies en tools oproepen:
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-realtime-mini");
// 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
Veelvoorkomende fouten en uitzonderingen
Authenticatiefouten: Als u authenticatiefouten ontvangt, controleer dan dat:
- Je Azure AI Foundry-resource is correct geconfigureerd
- Je API-sleutel of credential heeft de benodigde permissies
- De eindpunt-URL is correct en toegankelijk
WebSocket-verbindingsproblemen: VoiceLive gebruikt WebSocket-verbindingen. Zorg ervoor dat:
- Je netwerk maakt WebSocket-verbindingen mogelijk
- Firewallregels staan verbindingen toe
*.cognitiveservices.azure.com - Browserbeleid staat WebSocket- en microfoontoegang toe (voor browsergebruik)
Audioproblemen: Voor audiogerelateerde problemen:
- Controleer microfoonrechten in de browser
- Controleer of audioformaten (PCM16, PCM24) worden ondersteund
- Zorg voor een juiste audiocontext-instelling voor afspelen
Telemetrie / Gedistribueerd Traceren
De VoiceLive SDK ondersteunt gedistribueerd traceren via het @azure/core-tracing pakket. Traceren is standaardno-op — er worden geen spans aangemaakt tenzij je je aanmeldt door een OpenTelemetry-compatibele traceerprovider te registreren.
Hoe werkt het?
Wanneer traceren is ingeschakeld, creëert de SDK automatisch overschrijdsels voor de sessielevenscyclus:
connect (parent span — open for the entire session lifetime)
├── send session.update
├── send conversation.item.create
├── send response.create
├── recv session.created
├── recv response.done ← turn count incremented, token usage recorded
├── send response.cancel ← interruption count incremented
├── recv error ← error event recorded
└── close ← session-level counters finalized
Span-attributen volgen de Semantische Conventies van OpenTelemetry GenAI (gen_ai.system, gen_ai.operation.name, , gen_ai.request.modelenz.) plus VoiceLive-specifieke extensies (gen_ai.voice.session_id, gen_ai.voice.turn_count, gen_ai.voice.audio_bytes_sent, ...). Meetgegevens op sessieniveau worden geaggregeerd op de connect periode wanneer de sessie eindigt.
Tracing inschakelen (Node.js, CommonJS — aanbevolen)
Voor CommonJS-apps gebruik de standaard Azure SDK instrumentatiebrug:
npm install @azure/opentelemetry-instrumentation-azure-sdk @opentelemetry/instrumentation @opentelemetry/sdk-trace-node
const {
NodeTracerProvider,
SimpleSpanProcessor,
ConsoleSpanExporter,
} = require("@opentelemetry/sdk-trace-node");
const { registerInstrumentations } = require("@opentelemetry/instrumentation");
const { createAzureSdkInstrumentation } = require("@azure/opentelemetry-instrumentation-azure-sdk");
// 1. Configure an OpenTelemetry tracer provider
const provider = new NodeTracerProvider({
spanProcessors: [new SimpleSpanProcessor(new ConsoleSpanExporter())],
});
provider.register();
// 2. Register the Azure SDK instrumentation BEFORE requiring @azure/ai-voicelive
registerInstrumentations({
instrumentations: [createAzureSdkInstrumentation()],
});
// 3. Use VoiceLive — spans are emitted automatically
const { VoiceLiveClient } = require("@azure/ai-voicelive");
const { DefaultAzureCredential } = require("@azure/identity");
const client = new VoiceLiveClient(endpoint, new DefaultAzureCredential());
const session = client.createSession("gpt-realtime");
await session.connect(); // creates "connect" span
Schakel tracing in (Node.js ESM en browsers)
createAzureSdkInstrumentation vertrouwt op CommonJS require-hooks en produceert geen spans wanneer de SDK als ESM wordt geladen (d.w.z. "type": "module" pakketten of browser-bundlers zoals Vite). Voor die omgevingen registreer je een minimale Instrumenter direct via useInstrumenter@azure/core-tracing:
import { useInstrumenter } from "@azure/core-tracing";
import { trace, context } from "@opentelemetry/api";
useInstrumenter({
startSpan(name, spanOptions) {
const ctx = spanOptions.tracingContext ?? context.active();
const tracer = trace.getTracer(spanOptions.packageName ?? "@azure/ai-voicelive", spanOptions.packageVersion);
const span = tracer.startSpan(name, { attributes: spanOptions.spanAttributes }, ctx);
return {
span: {
end: () => span.end(),
setStatus: (s) => { if (s.status === "error") span.setStatus({ code: 2, message: String(s.error ?? "") }); },
setAttribute: (k, v) => span.setAttribute(k, v),
isRecording: () => span.isRecording(),
recordException: (e) => span.recordException(e),
},
tracingContext: trace.setSpan(ctx, span),
};
},
withContext: (ctx, fn, ...args) => context.with(ctx, fn, undefined, ...args),
parseTraceparentHeader: () => undefined,
createRequestHeaders: () => ({}),
});
Dit levert overspanningen op die identiek zijn aan de CommonJS-brug.
Complete, uitvoerbare samples:
- Node.js (ESM):
samples/telemetry/— console-exporteur en Azure Monitor variant.- Browser (Vite):
samples/telemetry-browser/— in-page span viewer.
Span-kenmerken
De SDK stelt attributen vast volgens GenAI Semantic Conventions:
| Attribute | Description |
|---|---|
az.namespace |
Altijd Microsoft.CognitiveServices |
gen_ai.system |
Altijd az.ai.voicelive |
gen_ai.operation.name |
connect, send, recv, of close |
gen_ai.request.model |
De modelnaam (bijv. gpt-realtime) |
gen_ai.voice.session_id |
Spraaksessie-ID van session.created |
gen_ai.voice.turn_count |
Totaal aantal voltooide responsbeurten (verbindingsspan) |
gen_ai.voice.interruption_count |
Aantal response.cancel gebeurtenissen (verbindingsspan) |
gen_ai.voice.audio_bytes_sent |
Totaal aantal verzonden audiobytes (verbindingsspan) |
gen_ai.voice.audio_bytes_received |
Totaal ontvangen audiobytes (verbindingsspan) |
gen_ai.voice.first_token_latency_ms |
Tijd van response.create tot eerste audio/tekst-delta |
gen_ai.usage.input_tokens |
Invoertokenaantal van response.done |
gen_ai.usage.output_tokens |
Output token count vanaf response.done |
Logboekregistratie
Het inschakelen van logboekregistratie kan helpen nuttige informatie over fouten te ontdekken. Om een log van WebSocket-berichten en -antwoorden te zien, zet je de AZURE_LOG_LEVEL omgevingsvariabele op info. U kunt logboekregistratie ook tijdens runtime inschakelen door setLogLevel aan te roepen in de @azure/logger:
import { setLogLevel } from "@azure/logger";
setLogLevel("info");
Voor meer gedetailleerde instructies over het inschakelen van logboeken, kunt u de @azure/logger pakketdocumentenbekijken.
Volgende stappen
Je kunt meer codevoorbeelden vinden via de volgende links:
Contributing
Als u een bijdrage wilt leveren aan deze bibliotheek, leest u de gids voor bijdragen voor meer informatie over het bouwen en testen van de code.
Azure SDK for JavaScript