Compartir a través de


Guía rápida: Crear un agente de voz en tiempo real Voice Live con el servicio Microsoft Foundry Agent

En este artículo, aprenderá a usar Voice Live con microsoft Foundry Agent Service y Azure Speech in Foundry Tools en el portal de Microsoft Foundry.

Puede crear y ejecutar una aplicación para interactuar en tiempo real con agentes mediante Voice Live.

  • El uso de agentes permite aprovechar una solicitud integrada y una configuración administradas dentro del propio agente, en lugar de especificar instrucciones en el código de sesión.

  • Los agentes encapsulan comportamientos y lógicas más complejos, lo que facilita la administración y actualización de flujos de conversación sin cambiar el código de cliente.

  • El enfoque del agente simplifica la integración. El identificador del agente se usa para conectarse y todas las opciones necesarias se controlan internamente, lo que reduce la necesidad de configuración manual en el código.

  • Esta separación también admite una mejor capacidad de mantenimiento y escalabilidad para escenarios en los que se necesitan varias experiencias conversacionales o variaciones de lógica de negocios.

Para usar voice Live API sin agentes, consulte el inicio rápido de Voice Live API.

Prerrequisitos

Sugerencia

Para usar Voice Live, no es necesario implementar un modelo de audio con el recurso de Microsoft Foundry. Voice Live está totalmente administrado y el modelo se implementa automáticamente. Para obtener más información sobre la disponibilidad de los modelos, consulte la documentación de información general de Voice Live.

Prueba de Voice Live en el área de juegos

Para probar la demostración de Voice Live, siga estos pasos:

  1. Inicie sesión en Microsoft Foundry. Asegúrese de que el conmutador New Foundry está desactivado. Estos pasos hacen referencia a Foundry (clásico).

  2. Seleccione Áreas de juegos en el panel izquierdo.

  3. En el icono Área de juegos de voz , seleccione Probar el área de juegos de voz.

  4. Seleccione Funcionalidades de voz por escenario>Voice Live.

    Captura de pantalla del filtrado de funcionalidades del servicio voz por escenario.

  5. Seleccione un agente que configuró en el área de pruebas Agentes.

    Captura de pantalla de la opción para traer un agente para Voice Live en el área de juegos de voz.

  6. Edite otras configuraciones según sea necesario, como voz,frecuencia de habla y detección de actividad de voz (VAD). El botón de alternancia Interacción proactiva posibilita que el agente hable primero durante la conversación.

  7. Seleccione Iniciar para empezar a hablar y seleccione Finalizar para finalizar la sesión de chat.

En este artículo, aprenderá a usar Voice Live con microsoft Foundry Agent Service mediante el SDK de VoiceLive para Python.

Documentación de referencia | Paquete (PyPi) | Ejemplos adicionales en GitHub

Puede crear y ejecutar una aplicación para interactuar en tiempo real con agentes mediante Voice Live.

  • El uso de agentes permite aprovechar una solicitud integrada y una configuración administradas dentro del propio agente, en lugar de especificar instrucciones en el código de sesión.

  • Los agentes encapsulan comportamientos y lógicas más complejos, lo que facilita la administración y actualización de flujos de conversación sin cambiar el código de cliente.

  • El enfoque del agente simplifica la integración. El identificador del agente se usa para conectarse y todas las opciones necesarias se controlan internamente, lo que reduce la necesidad de configuración manual en el código.

  • Esta separación también admite una mejor capacidad de mantenimiento y escalabilidad para escenarios en los que se necesitan varias experiencias conversacionales o variaciones de lógica de negocios.

Para usar voice Live API sin agentes, consulte el inicio rápido de Voice Live API.

Prerrequisitos

Sugerencia

Para usar Voice Live, no es necesario implementar un modelo de audio con el recurso de Microsoft Foundry. Voice Live está totalmente administrado y el modelo se implementa automáticamente. Para obtener más información sobre la disponibilidad de los modelos, consulte la documentación de información general de Voice Live.

Requisitos previos de Microsoft Entra ID

Para la autenticación sin clave recomendada con Microsoft Entra ID, debe hacer lo siguiente:

  • Instale la CLI de Azure utilizada para la autenticación sin clave con Microsoft Entra ID.
  • Asignar el rol Cognitive Services User a su cuenta de usuario. Puede asignar roles en el portal de Azure bajo control de acceso (IAM)>Agregar asignación de roles.

Configuración

  1. Cree una nueva carpeta voice-live-quickstart y vaya a la carpeta quickstart mediante el siguiente comando:

    mkdir voice-live-quickstart && cd voice-live-quickstart
    
  2. Cree un entorno virtual. Si ya tiene Instalado Python 3.10 o superior, puede crear un entorno virtual con los siguientes comandos:

    py -3 -m venv .venv
    .venv\scripts\activate
    

    La activación del entorno de Python significa que, al ejecutar python o pip desde la línea de comandos, se usa el intérprete de Python incluido en la carpeta .venv de la aplicación. Puede usar el comando deactivate para salir del entorno virtual de Python y, posteriormente, volver a activarlo cuando sea necesario.

    Sugerencia

    Se recomienda crear y activar un nuevo entorno de Python para instalar los paquetes que necesita para este tutorial. No instale paquetes en la instalación global de Python. Siempre debe usar un entorno virtual o conda al instalar paquetes de Python; de lo contrario, puede interrumpir la instalación global de Python.

  3. Cree un archivo denominado requirements.txt. Agregue los siguientes paquetes al archivo:

    azure-ai-voicelive[aiohttp]
    pyaudio
    python-dotenv
    azure-identity
    
  4. Instale los paquetes:

    pip install -r requirements.txt
    

Recuperación de información de recursos

Cree un nuevo archivo denominado .env en la carpeta donde desea ejecutar el código.

En el .env archivo, agregue las siguientes variables de entorno para la autenticación:

AZURE_VOICELIVE_ENDPOINT=<your_endpoint>
AZURE_VOICELIVE_PROJECT_NAME=<your_project_name>
AZURE_VOICELIVE_AGENT_ID=<your_agent_id>
AZURE_VOICELIVE_API_VERSION=2025-10-01

Reemplace los valores predeterminados por el nombre real del proyecto, el identificador del agente, la versión de API y la clave de API.

Nombre de la variable Importancia
AZURE_VOICELIVE_ENDPOINT Este valor se puede encontrar en la sección Claves y Punto de Conexión al examinar su recurso desde el portal de Azure.
AZURE_VOICELIVE_PROJECT_NAME Nombre del proyecto de Microsoft Foundry.
AZURE_VOICELIVE_AGENT_ID El identificador de tu agente de Microsoft Foundry.
AZURE_VOICELIVE_API_VERSION La versión de LA API que quiere usar. Por ejemplo: 2025-10-01.

Obtenga más información sobre la autenticación sin claves y la configuración de variables de entorno.

Iniciar una conversación

El código de ejemplo de esta guía de inicio rápido usa Microsoft Entra ID para la autenticación, ya que la integración actual solo admite este método de autenticación.

  1. Cree el archivo voice-live-agents-quickstart.py con el código siguiente:

    # -------------------------------------------------------------------------
    # Copyright (c) Microsoft Corporation. All rights reserved.
    # Licensed under the MIT License.
    # -------------------------------------------------------------------------
    from __future__ import annotations
    import os
    import sys
    import argparse
    import asyncio
    import base64
    from datetime import datetime
    import logging
    import queue
    import signal
    from typing import Union, Optional, TYPE_CHECKING, cast
    
    from azure.core.credentials import AzureKeyCredential
    from azure.core.credentials_async import AsyncTokenCredential
    from azure.identity.aio import AzureCliCredential, DefaultAzureCredential
    
    from azure.ai.voicelive.aio import connect
    from azure.ai.voicelive.models import (
        AudioEchoCancellation,
        AudioNoiseReduction,
        AzureStandardVoice,
        InputAudioFormat,
        Modality,
        OutputAudioFormat,
        RequestSession,
        ServerEventType,
        ServerVad
    )
    from dotenv import load_dotenv
    import pyaudio
    
    if TYPE_CHECKING:
        # Only needed for type checking; avoids runtime import issues
        from azure.ai.voicelive.aio import VoiceLiveConnection
    
    ## Change to the directory where this script is located
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    
    # Environment variable loading
    load_dotenv('./.env', override=True)
    
    # Set up logging
    ## Add folder for logging
    if not os.path.exists('logs'):
        os.makedirs('logs')
    
    ## Add timestamp for logfiles
    timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    
    ## Create conversation log filename
    logfilename = f"{timestamp}_conversation.log"
    
    ## Set up logging
    logging.basicConfig(
        filename=f'logs/{timestamp}_voicelive.log',
        filemode="w",
        format='%(asctime)s:%(name)s:%(levelname)s:%(message)s',
        level=logging.INFO
    )
    logger = logging.getLogger(__name__)
    
    class AudioProcessor:
        """
        Handles real-time audio capture and playback for the voice assistant.
    
        Threading Architecture:
        - Main thread: Event loop and UI
        - Capture thread: PyAudio input stream reading
        - Send thread: Async audio data transmission to VoiceLive
        - Playback thread: PyAudio output stream writing
        """
    
        loop: asyncio.AbstractEventLoop
    
        class AudioPlaybackPacket:
            """Represents a packet that can be sent to the audio playback queue."""
            def __init__(self, seq_num: int, data: Optional[bytes]):
                self.seq_num = seq_num
                self.data = data
    
        def __init__(self, connection):
            self.connection = connection
            self.audio = pyaudio.PyAudio()
    
            # Audio configuration - PCM16, 24kHz, mono as specified
            self.format = pyaudio.paInt16
            self.channels = 1
            self.rate = 24000
            self.chunk_size = 1200 # 50ms
    
            # Capture and playback state
            self.input_stream = None
    
            self.playback_queue: queue.Queue[AudioProcessor.AudioPlaybackPacket] = queue.Queue()
            self.playback_base = 0
            self.next_seq_num = 0
            self.output_stream: Optional[pyaudio.Stream] = None
    
            logger.info("AudioProcessor initialized with 24kHz PCM16 mono audio")
    
        def start_capture(self):
            """Start capturing audio from microphone."""
            def _capture_callback(
                in_data,      # data
                _frame_count,  # number of frames
                _time_info,    # dictionary
                _status_flags):
                """Audio capture thread - runs in background."""
                audio_base64 = base64.b64encode(in_data).decode("utf-8")
                asyncio.run_coroutine_threadsafe(
                    self.connection.input_audio_buffer.append(audio=audio_base64), self.loop
                )
                return (None, pyaudio.paContinue)
    
            if self.input_stream:
                return
    
            # Store the current event loop for use in threads
            self.loop = asyncio.get_event_loop()
    
            try:
                self.input_stream = self.audio.open(
                    format=self.format,
                    channels=self.channels,
                    rate=self.rate,
                    input=True,
                    frames_per_buffer=self.chunk_size,
                    stream_callback=_capture_callback,
                )
                logger.info("Started audio capture")
    
            except Exception:
                logger.exception("Failed to start audio capture")
                raise
    
        def start_playback(self):
            """Initialize audio playback system."""
            if self.output_stream:
                return
    
            remaining = bytes()
            def _playback_callback(
                _in_data,
                frame_count,  # number of frames
                _time_info,
                _status_flags):
    
                nonlocal remaining
                frame_count *= pyaudio.get_sample_size(pyaudio.paInt16)
    
                out = remaining[:frame_count]
                remaining = remaining[frame_count:]
    
                while len(out) < frame_count:
                    try:
                        packet = self.playback_queue.get_nowait()
                    except queue.Empty:
                        out = out + bytes(frame_count - len(out))
                        continue
                    except Exception:
                        logger.exception("Error in audio playback")
                        raise
    
                    if not packet or not packet.data:
                        # None packet indicates end of stream
                        logger.info("End of playback queue.")
                        break
    
                    if packet.seq_num < self.playback_base:
                        # skip requested
                        # ignore skipped packet and clear remaining
                        if len(remaining) > 0:
                            remaining = bytes()
                        continue
    
                    num_to_take = frame_count - len(out)
                    out = out + packet.data[:num_to_take]
                    remaining = packet.data[num_to_take:]
    
                if len(out) >= frame_count:
                    return (out, pyaudio.paContinue)
                else:
                    return (out, pyaudio.paComplete)
    
            try:
                self.output_stream = self.audio.open(
                    format=self.format,
                    channels=self.channels,
                    rate=self.rate,
                    output=True,
                    frames_per_buffer=self.chunk_size,
                    stream_callback=_playback_callback
                )
                logger.info("Audio playback system ready")
            except Exception:
                logger.exception("Failed to initialize audio playback")
                raise
    
        def _get_and_increase_seq_num(self):
            seq = self.next_seq_num
            self.next_seq_num += 1
            return seq
    
        def queue_audio(self, audio_data: Optional[bytes]) -> None:
            """Queue audio data for playback."""
            self.playback_queue.put(
                AudioProcessor.AudioPlaybackPacket(
                    seq_num=self._get_and_increase_seq_num(),
                    data=audio_data))
    
        def skip_pending_audio(self):
            """Skip current audio in playback queue."""
            self.playback_base = self._get_and_increase_seq_num()
    
        def shutdown(self):
            """Clean up audio resources."""
            if self.input_stream:
                self.input_stream.stop_stream()
                self.input_stream.close()
                self.input_stream = None
    
            logger.info("Stopped audio capture")
    
            # Inform thread to complete
            if self.output_stream:
                self.skip_pending_audio()
                self.queue_audio(None)
                self.output_stream.stop_stream()
                self.output_stream.close()
                self.output_stream = None
    
            logger.info("Stopped audio playback")
    
            if self.audio:
                self.audio.terminate()
    
            logger.info("Audio processor cleaned up")
    
    class BasicVoiceAssistant:
        """
            Basic voice assistant implementing the VoiceLive SDK patterns with Foundry Agent.
            This sample also demonstrates how to collect a conversation log of user and agent interactions.
        """
    
    
        def __init__(
            self,
            endpoint: str,
            credential: Union[AzureKeyCredential, AsyncTokenCredential],
            agent_id: str,
            foundry_project_name: str,
            voice: str,
        ):
    
            self.endpoint = endpoint
            self.credential = credential
            self.agent_id = agent_id
            self.foundry_project_name = foundry_project_name
            self.voice = voice
            self.connection: Optional["VoiceLiveConnection"] = None
            self.audio_processor: Optional[AudioProcessor] = None
            self.session_ready = False
            self.conversation_started = False
            self._active_response = False
            self._response_api_done = False
    
        async def start(self):
            """Start the voice assistant session."""
            try:
                logger.info("Connecting to VoiceLive API with Foundry agent connection %s for project %s", self.agent_id, self.foundry_project_name)
    
                # Get agent access token
                agent_access_token = (await DefaultAzureCredential().get_token("https://ai.azure.com/.default")).token
                logger.info("Obtained agent access token")
    
                # Connect to VoiceLive WebSocket API
                async with connect(
                    endpoint=self.endpoint,
                    credential=self.credential,
                    query={
                        "agent-id": self.agent_id,
                        "agent-project-name": self.foundry_project_name,
                        "agent-access-token": agent_access_token
                    },
                ) as connection:
                    conn = connection
                    self.connection = conn
    
                    # Initialize audio processor
                    ap = AudioProcessor(conn)
                    self.audio_processor = ap
    
                    # Configure session for voice conversation
                    await self._setup_session()
    
                    # Start audio systems
                    ap.start_playback()
    
                    logger.info("Voice assistant ready! Start speaking...")
                    print("\n" + "=" * 60)
                    print("🎤 VOICE ASSISTANT READY")
                    print("Start speaking to begin conversation")
                    print("Press Ctrl+C to exit")
                    print("=" * 60 + "\n")
    
                    # Process events
                    await self._process_events()
            finally:
                if self.audio_processor:
                    self.audio_processor.shutdown()
    
        async def _setup_session(self):
            """Configure the VoiceLive session for audio conversation."""
            logger.info("Setting up voice conversation session...")
    
            # Create voice configuration
            voice_config: Union[AzureStandardVoice, str]
            if self.voice.startswith("en-US-") or self.voice.startswith("en-CA-") or "-" in self.voice:
                # Azure voice
                voice_config = AzureStandardVoice(name=self.voice)
            else:
                # OpenAI voice (alloy, echo, fable, onyx, nova, shimmer)
                voice_config = self.voice
    
            # Create turn detection configuration
            turn_detection_config = ServerVad(
                threshold=0.5,
                prefix_padding_ms=300,
                silence_duration_ms=500)
    
            # Create session configuration
            session_config = RequestSession(
                modalities=[Modality.TEXT, Modality.AUDIO],
                voice=voice_config,
                input_audio_format=InputAudioFormat.PCM16,
                output_audio_format=OutputAudioFormat.PCM16,
                turn_detection=turn_detection_config,
                input_audio_echo_cancellation=AudioEchoCancellation(),
                input_audio_noise_reduction=AudioNoiseReduction(type="azure_deep_noise_suppression"),
            )
    
            conn = self.connection
            assert conn is not None, "Connection must be established before setting up session"
            await conn.session.update(session=session_config)
    
            logger.info("Session configuration sent")
    
        async def _process_events(self):
            """Process events from the VoiceLive connection."""
            try:
                conn = self.connection
                assert conn is not None, "Connection must be established before processing events"
                async for event in conn:
                    await self._handle_event(event)
            except Exception:
                logger.exception("Error processing events")
                raise
    
        async def _handle_event(self, event):
            """Handle different types of events from VoiceLive."""
            logger.debug("Received event: %s", event.type)
            ap = self.audio_processor
            conn = self.connection
            assert ap is not None, "AudioProcessor must be initialized"
            assert conn is not None, "Connection must be established"
    
            if event.type == ServerEventType.SESSION_UPDATED:
                logger.info("Session ready: %s", event.session.id)
                await write_conversation_log(f"SessionID: {event.session.id}")
                await write_conversation_log(f"Model: {event.session.model}")
                await write_conversation_log(f"Voice: {event.session.voice}")
                await write_conversation_log(f"Instructions: {event.session.instructions}")
                await write_conversation_log(f"")
                self.session_ready = True
    
                # Invoke Proactive greeting
                if not self.conversation_started:
                    self.conversation_started = True
                    logger.info("Sending proactive greeting request")
                    try:
                        await conn.response.create()
    
                    except Exception:
                        logger.exception("Failed to send proactive greeting request")
    
                # Start audio capture once session is ready
                ap.start_capture()
    
            elif event.type == ServerEventType.CONVERSATION_ITEM_INPUT_AUDIO_TRANSCRIPTION_COMPLETED:
                print(f'👤 You said:\t{event.get("transcript", "")}')
                await write_conversation_log(f'User Input:\t{event.get("transcript", "")}')
    
            elif event.type == ServerEventType.RESPONSE_TEXT_DONE:
                print(f'🤖 Agent responded with text:\t{event.get("text", "")}')
                await write_conversation_log(f'Agent Text Response:\t{event.get("text", "")}')
    
            elif event.type == ServerEventType.RESPONSE_AUDIO_TRANSCRIPT_DONE:
                print(f'🤖 Agent responded with audio transcript:\t{event.get("transcript", "")}')
                await write_conversation_log(f'Agent Audio Response:\t{event.get("transcript", "")}')
    
            elif event.type == ServerEventType.INPUT_AUDIO_BUFFER_SPEECH_STARTED:
                logger.info("User started speaking - stopping playback")
                print("🎤 Listening...")
    
                ap.skip_pending_audio()
    
                # Only cancel if response is active and not already done
                if self._active_response and not self._response_api_done:
                    try:
                        await conn.response.cancel()
                        logger.debug("Cancelled in-progress response due to barge-in")
                    except Exception as e:
                        if "no active response" in str(e).lower():
                            logger.debug("Cancel ignored - response already completed")
                        else:
                            logger.warning("Cancel failed: %s", e)
    
            elif event.type == ServerEventType.INPUT_AUDIO_BUFFER_SPEECH_STOPPED:
                logger.info("🎤 User stopped speaking")
                print("🤔 Processing...")
    
            elif event.type == ServerEventType.RESPONSE_CREATED:
                logger.info("🤖 Assistant response created")
                self._active_response = True
                self._response_api_done = False
    
            elif event.type == ServerEventType.RESPONSE_AUDIO_DELTA:
                logger.debug("Received audio delta")
                ap.queue_audio(event.delta)
    
            elif event.type == ServerEventType.RESPONSE_AUDIO_DONE:
                logger.info("🤖 Assistant finished speaking")
                print("🎤 Ready for next input...")
    
            elif event.type == ServerEventType.RESPONSE_DONE:
                logger.info("✅ Response complete")
                self._active_response = False
                self._response_api_done = True
    
            elif event.type == ServerEventType.ERROR:
                msg = event.error.message
                if "Cancellation failed: no active response" in msg:
                    logger.debug("Benign cancellation error: %s", msg)
                else:
                    logger.error("❌ VoiceLive error: %s", msg)
                    print(f"Error: {msg}")
    
            elif event.type == ServerEventType.CONVERSATION_ITEM_CREATED:
                logger.debug("Conversation item created: %s", event.item.id)
    
            else:
                logger.debug("Unhandled event type: %s", event.type)
    
    async def write_conversation_log(message: str) -> None:
        """Write a message to the conversation log."""
        def _write_to_file():
            with open(f'logs/{logfilename}', 'a', encoding='utf-8') as conversation_log:
                conversation_log.write(message + "\n")
    
        await asyncio.to_thread(_write_to_file)
    
    def parse_arguments():
        """Parse command line arguments."""
        parser = argparse.ArgumentParser(
            description="Basic Voice Assistant using Azure VoiceLive SDK",
            formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        )
    
        parser.add_argument(
            "--api-key",
            help="Azure VoiceLive API key. If not provided, will use AZURE_VOICELIVE_API_KEY environment variable.",
            type=str,
            default=os.environ.get("AZURE_VOICELIVE_API_KEY"),
        )
    
        parser.add_argument(
            "--endpoint",
            help="Azure VoiceLive endpoint",
            type=str,
            default=os.environ.get("AZURE_VOICELIVE_ENDPOINT", "https://your-resource-name.services.ai.azure.com/"),
        )
    
        parser.add_argument(
            "--agent_id",
            help="Foundry agent ID to use",
            type=str,
            default=os.environ.get("AZURE_VOICELIVE_AGENT_ID", ""),
        )
    
        parser.add_argument(
            "--foundry_project_name",
            help="Foundry project name to use",
            type=str,
            default=os.environ.get("AZURE_VOICELIVE_PROJECT_NAME", ""),
        )
    
        parser.add_argument(
            "--voice",
            help="Voice to use for the assistant. E.g. alloy, echo, fable, en-US-AvaNeural, en-US-GuyNeural",
            type=str,
            default=os.environ.get("AZURE_VOICELIVE_VOICE", "en-US-Ava:DragonHDLatestNeural"),
        )
    
        parser.add_argument(
            "--use-token-credential", help="Use Azure token credential instead of API key", action="store_true", default=True
        )
    
        parser.add_argument("--verbose", help="Enable verbose logging", action="store_true")
    
        return parser.parse_args()
    
    
    def main():
        """Main function."""
        args = parse_arguments()
    
        # Set logging level
        if args.verbose:
            logging.getLogger().setLevel(logging.DEBUG)
    
        # Validate credentials
        if not args.api_key and not args.use_token_credential:
            print("❌ Error: No authentication provided")
            print("Please provide an API key using --api-key or set AZURE_VOICELIVE_API_KEY environment variable,")
            print("or use --use-token-credential for Azure authentication.")
            sys.exit(1)
    
        # Create client with appropriate credential
        credential: Union[AzureKeyCredential, AsyncTokenCredential]
        if args.use_token_credential:
            credential = AzureCliCredential()  # or DefaultAzureCredential() if needed
            logger.info("Using Azure token credential")
        else:
            credential = AzureKeyCredential(args.api_key)
            logger.info("Using API key credential")
    
        # Create and start voice assistant
        assistant = BasicVoiceAssistant(
            endpoint=args.endpoint,
            credential=credential,
            agent_id=args.agent_id,
            foundry_project_name=args.foundry_project_name,
            voice=args.voice,
        )
    
        # Setup signal handlers for graceful shutdown
        def signal_handler(_sig, _frame):
            logger.info("Received shutdown signal")
            raise KeyboardInterrupt()
    
        signal.signal(signal.SIGINT, signal_handler)
        signal.signal(signal.SIGTERM, signal_handler)
    
        # Start the assistant
        try:
            asyncio.run(assistant.start())
        except KeyboardInterrupt:
            print("\n👋 Voice assistant shut down. Goodbye!")
        except Exception as e:
            print("Fatal Error: ", e)
    
    if __name__ == "__main__":
        # Check audio system
        try:
            p = pyaudio.PyAudio()
            # Check for input devices
            input_devices = [
                i
                for i in range(p.get_device_count())
                if cast(Union[int, float], p.get_device_info_by_index(i).get("maxInputChannels", 0) or 0) > 0
            ]
            # Check for output devices
            output_devices = [
                i
                for i in range(p.get_device_count())
                if cast(Union[int, float], p.get_device_info_by_index(i).get("maxOutputChannels", 0) or 0) > 0
            ]
            p.terminate()
    
            if not input_devices:
                print("❌ No audio input devices found. Please check your microphone.")
                sys.exit(1)
            if not output_devices:
                print("❌ No audio output devices found. Please check your speakers.")
                sys.exit(1)
    
        except Exception as e:
            print(f"❌ Audio system check failed: {e}")
            sys.exit(1)
    
        print("🎙️  Basic Voice Assistant with Azure VoiceLive SDK")
        print("=" * 50)
    
        # Run the assistant
        main()
    
  2. Inicie sesión en Azure con el siguiente comando:

    az login
    
  3. Ejecución del archivo de Python.

    python voice-live-agents-quickstart.py
    
  4. Puede empezar a hablar con el agente y escuchar respuestas. Puede interrumpir el modelo hablando. Escriba "Ctrl+C" para salir de la conversación.

Salida

La salida del script se imprime en la consola. Verá mensajes que indican el estado de la conexión, la secuencia de audio y la reproducción. El audio se reproduce a través de los altavoces o auriculares.

🎙️  Basic Voice Assistant with Azure VoiceLive SDK
==================================================

============================================================
🎤 VOICE ASSISTANT READY
Start speaking to begin conversation
Press Ctrl+C to exit
============================================================

🎤 Listening...
🤔 Processing...
👤 You said:  User Input:       Hello.
🎤 Ready for next input...
🤖 Agent responded with audio transcript:  Agent Audio Response:        Hello! I'm Tobi the agent. How can I assist you today?
🎤 Listening...
🤔 Processing...
👤 You said:  User Input:       What are the opening hours of the Eiffel Tower?
🎤 Ready for next input...
🤖 Agent responded with audio transcript:  Agent Audio Response:        The Eiffel Tower's opening hours can vary depending on the season and any special events or maintenance. Generally, the Eiffel Tower is open every day of the year, with the following typical hours:

- Mid-June to early September: 9:00 AM to 12:45 AM (last elevator ride up at 12:00 AM)
- Rest of the year: 9:30 AM to 11:45 PM (last elevator ride up at 11:00 PM)

These times can sometimes change, so it's always best to check the official Eiffel Tower website or contact them directly for the most up-to-date information before your visit.

Would you like me to help you find the official website or any other details about visiting the Eiffel Tower?

👋 Voice assistant shut down. Goodbye!

El script que ejecutó crea un archivo de registro denominado <timestamp>_voicelive.log en la logs carpeta .

logging.basicConfig(
    filename=f'logs/{timestamp}_voicelive.log',
    filemode="w",
    format='%(asctime)s:%(name)s:%(levelname)s:%(message)s',
    level=logging.INFO
)

El voicelive.log archivo contiene información sobre la conexión a Voice Live API, incluidos los datos de solicitud y respuesta. Puede ver el archivo de registro para ver los detalles de la conversación.

2025-10-28 10:26:12,768:__main__:INFO:Using Azure token credential
2025-10-28 10:26:12,769:__main__:INFO:Connecting to VoiceLive API with Foundry agent connection asst_JVSR1R9XpUBxZP1c4YUWy2GA for project myservice-voicelive-eus2
2025-10-28 10:26:12,770:azure.identity.aio._credentials.environment:INFO:No environment configuration found.
2025-10-28 10:26:12,779:azure.identity.aio._credentials.managed_identity:INFO:ManagedIdentityCredential will use IMDS
2025-10-28 10:26:12,780:azure.core.pipeline.policies.http_logging_policy:INFO:Request URL: 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=REDACTED&resource=REDACTED'
Request method: 'GET'
Request headers:
    'User-Agent': 'azsdk-python-identity/1.25.1 Python/3.11.9 (Windows-10-10.0.26200-SP0)'
No body was attached to the request
2025-10-28 10:26:14,527:azure.identity.aio._credentials.chained:INFO:DefaultAzureCredential acquired a token from AzureCliCredential
2025-10-28 10:26:14,527:__main__:INFO:Obtained agent access token
2025-10-28 10:26:16,036:azure.identity.aio._internal.decorators:INFO:AzureCliCredential.get_token succeeded
2025-10-28 10:26:16,575:__main__:INFO:AudioProcessor initialized with 24kHz PCM16 mono audio
2025-10-28 10:26:16,575:__main__:INFO:Setting up voice conversation session...
2025-10-28 10:26:16,576:__main__:INFO:Session configuration sent
2025-10-28 10:26:16,833:__main__:INFO:Audio playback system ready
2025-10-28 10:26:16,833:__main__:INFO:Voice assistant ready! Start speaking...
2025-10-28 10:26:17,691:__main__:INFO:Session ready: sess_Oics8h0KxxxxPne71S1k
2025-10-28 10:26:17,713:__main__:INFO:Started audio capture
2025-10-28 10:26:18,413:__main__:INFO:User started speaking - stopping playback
2025-10-28 10:26:19,007:__main__:INFO:\U0001f3a4 User stopped speaking
2025-10-28 10:26:24,009:__main__:INFO:User started speaking - stopping playback
2025-10-28 10:26:24,771:__main__:INFO:\U0001f3a4 User stopped speaking
2025-10-28 10:26:24,887:__main__:INFO:\U0001f916 Assistant response created
2025-10-28 10:26:30,273:__main__:INFO:\U0001f916 Assistant finished speaking
2025-10-28 10:26:30,275:__main__:INFO:\u2705 Response complete
2025-10-28 10:26:38,461:__main__:INFO:User started speaking - stopping playback
2025-10-28 10:26:39,909:__main__:INFO:\U0001f3a4 User stopped speaking
2025-10-28 10:26:40,090:__main__:INFO:\U0001f916 Assistant response created
2025-10-28 10:26:44,631:__main__:INFO:\U0001f916 Assistant finished speaking
2025-10-28 10:26:44,634:__main__:INFO:\u2705 Response complete
2025-10-28 10:26:47,190:__main__:INFO:User started speaking - stopping playback
2025-10-28 10:26:48,959:__main__:INFO:\U0001f3a4 User stopped speaking
2025-10-28 10:26:49,246:__main__:INFO:\U0001f916 Assistant response created
2025-10-28 10:27:01,306:__main__:INFO:\U0001f916 Assistant finished speaking
2025-10-28 10:27:01,315:__main__:INFO:\u2705 Response complete
2025-10-28 10:27:09,586:__main__:INFO:Received shutdown signal
2025-10-28 10:27:09,634:__main__:INFO:Stopped audio capture
2025-10-28 10:27:09,758:__main__:INFO:Stopped audio playback
2025-10-28 10:27:09,759:__main__:INFO:Audio processor cleaned up

Además, se crea un archivo de registro de sesión en la logs carpeta con el nombre <timestamp>_conversation.log. Este archivo contiene información detallada sobre la sesión, incluidos los datos de solicitud y respuesta.

SessionID: sess_Oics8h0KxxxxPne71S1k
Model: gpt-4.1-mini
Voice: {'name': 'en-US-Ava:DragonHDLatestNeural', 'type': 'azure-standard'}
Instructions: You are a helpful agent named 'Tobi the agent'.

User Input:	Hello.
Agent Audio Response:	Hello! I'm Tobi the agent. How can I assist you today?
User Input:	What are the opening hours of the Eiffel Tower?
Agent Audio Response:	The Eiffel Tower's opening hours can vary depending on the season and any special events or maintenance. Generally, the Eiffel Tower is open every day of the year, with the following typical hours:

- Mid-June to early September: 9:00 AM to 12:45 AM (last elevator ride up at 12:00 AM)
- Rest of the year: 9:30 AM to 11:45 PM (last elevator ride up at 11:00 PM)

These times can sometimes change, so it's always best to check the official Eiffel Tower website or contact them directly for the most up-to-date information before your visit.

Would you like me to help you find the official website or any other details about visiting the Eiffel Tower?

Estas son las principales diferencias entre el registro técnico y el registro de conversación:

Aspecto Registro de conversaciones Registro técnico
Audiencia Usuarios empresariales, revisores de contenido Desarrolladores, operaciones de TI
Contenido Lo que se dijo en las conversaciones Funcionamiento del sistema
Level Nivel de aplicación/conversación Nivel de sistema e infraestructura
Solución de problemas "¿Qué dijo el agente?" "¿Por qué se produjo un error en la conexión?"

Ejemplo: Si el agente no responde, comprobaría lo siguiente:

  • voicelive.log → "Error de conexión de WebSocket" o "Error de secuencia de audio"
  • conversation.log → "¿El usuario dijo algo?"

Ambos registros son complementarios: registros de conversación para análisis y pruebas de conversación, registros técnicos para diagnósticos del sistema.

Registro técnico

Propósito: depuración técnica y supervisión del sistema

Contenido:

  • Eventos de conexión de WebSocket
  • Estado de la secuencia de audio
  • Mensajes de error y rastros de pila
  • Eventos de nivel del sistema (session.created, response.done, etc.)
  • Problemas de conectividad de red
  • Diagnósticos de procesamiento de audio

Formato: registro estructurado con marcas de tiempo, niveles de registro y detalles técnicos

Casos de uso:

  • Solución de problemas de conexión
  • Supervisión del rendimiento del sistema
  • Solución de problemas de audio
  • Análisis de desarrolladores y operaciones

Registro de conversaciones

Propósito: transcripción de conversaciones y seguimiento de la experiencia del usuario

Contenido:

  • Identificación del agente y del proyecto
  • Detalles de configuración de sesión
  • Transcripciones de usuario: "Cuéntame una historia", "Detener"
  • Respuestas del agente: texto completo del artículo y respuestas de seguimiento
  • Flujo de conversación e interacciones

Formato: Texto sin formato, formato de conversación comprensible para humanos

Casos de uso:

  • Análisis de la calidad de la conversación
  • Revisar lo que se dijo realmente
  • Descripción de las interacciones del usuario y las respuestas del agente
  • Análisis de contenido o negocio

Proyectos basados en centros

El inicio rápido utiliza proyectos de Foundry en lugar de proyectos basados en hub. Si tiene un proyecto basado en concentrador, puede seguir usando el inicio rápido con algunas modificaciones.

Para usar la guía de inicio rápido con un proyecto basado en un concentrador, debe recuperar la cadena de conexión de su agente y utilizarla en lugar de la foundry_project_name. Puede encontrar la cadena de conexión en Azure Portal en el proyecto Foundry.

Información general

En proyectos basados en concentradores, use la cadena de conexión en lugar del nombre del proyecto para conectar su agente.

Además, debe obtener un token de autenticación independiente del ámbito "https://ml.azure.com/.default".

Realice los siguientes cambios en el código de inicio rápido:

  1. Reemplace todas las instancias de foundry_project_name por agent-connection-string las líneas siguientes en el código para cambiar la autenticación:

  2. Reemplace el ámbito del token de autenticación en la línea 307:

    # Get agent access token
    agent_access_token = (await DefaultAzureCredential().get_token("https://ml.azure.com/.default")).token
    logger.info("Obtained agent access token")
    
  3. Reemplace el parámetro de consulta en la línea 316:

    # Connect to VoiceLive WebSocket API
    async with connect(
        endpoint=self.endpoint,
        credential=self.credential,
        query={
            "agent-id": self.agent_id,
            "agent-connection-string": self.agent-connection-string,
            "agent-access-token": agent_access_token
        },
    ) as connection:
        conn = connection
        self.connection = conn
    

En este artículo, aprenderá a usar Voice Live con el servicio de agente Foundry mediante el SDK de VoiceLive para C#.

Documentación de referencia | Paquete (NuGet) | Ejemplos adicionales en GitHub

Puede crear y ejecutar una aplicación para interactuar en tiempo real con agentes mediante Voice Live.

  • El uso de agentes permite aprovechar una solicitud integrada y una configuración administradas dentro del propio agente, en lugar de especificar instrucciones en el código de sesión.

  • Los agentes encapsulan comportamientos y lógicas más complejos, lo que facilita la administración y actualización de flujos de conversación sin cambiar el código de cliente.

  • El enfoque del agente simplifica la integración. El identificador del agente se usa para conectarse y todas las opciones necesarias se controlan internamente, lo que reduce la necesidad de configuración manual en el código.

  • Esta separación también admite una mejor capacidad de mantenimiento y escalabilidad para escenarios en los que se necesitan varias experiencias conversacionales o variaciones de lógica de negocios.

Para usar voice Live API sin agentes, consulte el inicio rápido de Voice Live API.

Prerrequisitos

Iniciar una conversación de voz

Siga estos pasos para crear una aplicación de consola e instalar el SDK de Voz.

  1. Abra una ventana de comandos en la carpeta donde desee crear el nuevo proyecto. Ejecute este comando para crear una aplicación de consola con la CLI de .NET.

    dotnet new console
    

    Este comando crea el archivo Program.cs en el directorio del proyecto.

  2. Instale el SDK de Voice Live, Azure Identity y NAudio y otros paquetes necesarios en el nuevo proyecto con la CLI de .NET.

    dotnet add package Azure.AI.VoiceLive
    dotnet add package Azure.Identity
    dotnet add package NAudio
    dotnet add package System.CommandLine --version 2.0.0-beta4.22272.1
    dotnet add package Microsoft.Extensions.Configuration.Json
    dotnet add package Microsoft.Extensions.Configuration.EnvironmentVariables
    dotnet add package Microsoft.Extensions.Logging.Console
    
  3. Cree un nuevo archivo denominado appsettings.json en la carpeta donde desea ejecutar el código. En ese archivo, agregue el siguiente contenido JSON:

    {
      "VoiceLive": {
        "Endpoint": "https://your-resource-name.services.ai.azure.com/",
        "Voice": "en-US-Ava:DragonHDLatestNeural"
      },
      "Agent": {
        "Id": "your-agent-id",
        "ProjectName": "your-agent-project-name"
      },  
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Azure.AI.VoiceLive": "Debug"
        }
      }
    }
    

    El código de ejemplo de este inicio rápido usa Microsoft Entra ID para la autenticación, ya que la integración actual solo admite este método de autenticación.

    Obtenga más información sobre la autenticación sin claves y la configuración de variables de entorno.

  4. En el archivo csharp.csproj , agregue la siguiente información para conectar el appsettings.json:

    <ItemGroup>
    <None Update="appsettings.json">
        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    </ItemGroup>
    
  5. Reemplace el contenido de Program.cs por el código siguiente. Este código crea un agente de voz básico mediante uno de los modelos integrados. Para obtener una versión más detallada, consulte el ejemplo en GitHub.

    // Copyright (c) Microsoft Corporation. All rights reserved.
    // Licensed under the MIT License.
    
    using System;
    using System.CommandLine;
    using System.CommandLine.Invocation;
    using System.Threading;
    using System.Web;
    using System.Threading.Tasks;
    using System.Threading.Channels;
    using System.Collections.Generic;
    using Azure.AI.VoiceLive;
    using Azure.Core;
    using Azure.Core.Pipeline;
    using Azure.Identity;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Logging;
    using NAudio.Wave;
    
    namespace Azure.AI.VoiceLive.Samples
    {
        /// <summary>
        /// FILE: Program.cs (Agent Quickstart - Consolidated)
        /// </summary>
        /// <remarks>
        /// DESCRIPTION:
        ///     This consolidated sample demonstrates connecting to a Foundry agent via the VoiceLive SDK,
        ///     creating a voice assistant that can engage in natural conversation with proper interruption
        ///     handling. Instead of using a direct model, this connects to a deployed agent in Foundry.
        ///     
        ///     All necessary code has been consolidated into this single file for easy distribution and execution.
        ///
        /// USAGE:
        ///     dotnet run --agent-id <agent-id> --agent-project-name <project-name>
        ///
        ///     Set the environment variables with your own values before running the sample:
        ///     1) AZURE_AGENT_ID - The Foundry agent ID
        ///     2) AZURE_AGENT_PROJECT_NAME - The Foundry agent project name  
        ///     3) AZURE_VOICELIVE_API_KEY - The Azure VoiceLive API key (still needed for VoiceLive service)
        ///     4) AZURE_VOICELIVE_ENDPOINT - The Azure VoiceLive endpoint
        ///
        ///     Note: Agent access token is generated automatically using DefaultAzureCredential.
        ///     Ensure you are authenticated with Azure CLI or have appropriate credentials configured.
        ///
        ///     Or update appsettings.json with your values.
        ///
        /// REQUIREMENTS:
        ///     - Azure.AI.VoiceLive
        ///     - Azure.Identity
        ///     - NAudio (for audio capture and playback)
        ///     - Microsoft.Extensions.Configuration
        ///     - System.CommandLine
        ///     - System.Threading.Channels
        /// </remarks>
        public class Program
        {
            /// <summary>
            /// Main entry point for the Voice Assistant sample.
            /// </summary>
            /// <param name="args"></param>
            /// <returns></returns>
            public static async Task<int> Main(string[] args)
            {
                // Create command line interface
                var rootCommand = CreateRootCommand();
                return await rootCommand.InvokeAsync(args).ConfigureAwait(false);
            }
    
            private static RootCommand CreateRootCommand()
            {
                var rootCommand = new RootCommand("Voice Assistant connecting to Foundry Agent via VoiceLive SDK");
    
                var apiKeyOption = new Option<string?>(
                    "--api-key",
                    "Azure VoiceLive API key. If not provided, will use AZURE_VOICELIVE_API_KEY environment variable.");
    
                var endpointOption = new Option<string>(
                    "--endpoint",
                    () => "wss://api.voicelive.com/v1",
                    "Azure VoiceLive endpoint");
    
                var agentIdOption = new Option<string>(
                    "--agent-id",
                    "Foundry agent ID");
    
                var agentProjectNameOption = new Option<string>(
                    "--agent-project-name", 
                    "Foundry agent project name");
    
                var voiceOption = new Option<string>(
                    "--voice",
                    () => "en-US-AvaNeural",
                    "Voice to use for the assistant");
    
                // Currently Foundry Agent Integration only supports token authentication
                var useTokenCredentialOption = new Option<bool>(
                    "--use-token-credential",
                    () => true,
                    "Use Azure token credential instead of API key");
    
                var verboseOption = new Option<bool>(
                    "--verbose",
                    "Enable verbose logging");
    
                rootCommand.AddOption(apiKeyOption);
                rootCommand.AddOption(endpointOption);
                rootCommand.AddOption(agentIdOption);
                rootCommand.AddOption(agentProjectNameOption);
                rootCommand.AddOption(voiceOption);
                rootCommand.AddOption(useTokenCredentialOption);
                rootCommand.AddOption(verboseOption);
    
                rootCommand.SetHandler(async (
                    string? apiKey,
                    string endpoint,
                    string? agentId,
                    string? agentProjectName,
                    string voice,
                    bool useTokenCredential,
                    bool verbose) =>
                {
                    await RunVoiceAssistantAsync(apiKey, endpoint, agentId, agentProjectName, voice, useTokenCredential, verbose).ConfigureAwait(false);
                },
                apiKeyOption,
                endpointOption,
                agentIdOption,
                agentProjectNameOption,
                voiceOption,
                useTokenCredentialOption,
                verboseOption);
    
                return rootCommand;
            }
    
            private static async Task RunVoiceAssistantAsync(
                string? apiKey,
                string endpoint,
                string? agentId,
                string? agentProjectName,
                string voice,
                bool useTokenCredential,
                bool verbose)
            {
                // Setup configuration
                var configuration = new ConfigurationBuilder()
                    .AddJsonFile("appsettings.json", optional: true)
                    .AddEnvironmentVariables()
                    .Build();
    
                // Override with command line values if provided
                apiKey ??= configuration["VoiceLive:ApiKey"] ?? Environment.GetEnvironmentVariable("AZURE_VOICELIVE_API_KEY");
                endpoint = configuration["VoiceLive:Endpoint"] ?? endpoint;
                agentId ??= configuration["Agent:Id"] ?? Environment.GetEnvironmentVariable("AZURE_AGENT_ID");
                agentProjectName ??= configuration["Agent:ProjectName"] ?? Environment.GetEnvironmentVariable("AZURE_AGENT_PROJECT_NAME");
                voice = configuration["VoiceLive:Voice"] ?? voice;
    
                // Setup logging
                using var loggerFactory = LoggerFactory.Create(builder =>
                {
                    builder.AddConsole();
                    if (verbose)
                    {
                        builder.SetMinimumLevel(LogLevel.Debug);
                    }
                    else
                    {
                        builder.SetMinimumLevel(LogLevel.Information);
                    }
                });
    
                var logger = loggerFactory.CreateLogger<Program>();
    
                // Validate agent credentials
                if (string.IsNullOrEmpty(agentId) || string.IsNullOrEmpty(agentProjectName))
                {
                    Console.WriteLine("❌ Error: Agent parameters missing");
                    Console.WriteLine("Please provide agent parameters:");
                    Console.WriteLine("  --agent-id (or AZURE_AGENT_ID environment variable)");
                    Console.WriteLine("  --agent-project-name (or AZURE_AGENT_PROJECT_NAME environment variable)");
                    Console.WriteLine("Note: Agent access token will be generated automatically using Azure credentials");
                    return;
                }
    
                // Validate VoiceLive credentials (still needed for the VoiceLive service)
                if (string.IsNullOrEmpty(apiKey) && !useTokenCredential)
                {
                    Console.WriteLine("❌ Error: No VoiceLive authentication provided");
                    Console.WriteLine("Please provide an API key using --api-key or set AZURE_VOICELIVE_API_KEY environment variable,");
                    Console.WriteLine("or use --use-token-credential for Azure authentication.");
                    return;
                }
    
                // Generate agent access token using Azure credentials
                string agentAccessToken;
                try
                {
                    logger.LogInformation("Generating agent access token using DefaultAzureCredential...");
                    var credential = new DefaultAzureCredential();
                    var tokenRequestContext = new TokenRequestContext(new[] { "https://ai.azure.com/.default" });
                    var accessToken = await credential.GetTokenAsync(tokenRequestContext, default).ConfigureAwait(false);
                    agentAccessToken = accessToken.Token;
                    logger.LogInformation("Obtained agent access token successfully");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"❌ Error generating agent access token: {ex.Message}");
                    Console.WriteLine("Please ensure you are authenticated with Azure CLI or have appropriate Azure credentials configured.");
                    return;
                }
    
                // Check audio system before starting
                if (!CheckAudioSystem(logger))
                {
                    return;
                }
    
                try
                {
                    // Append agent parameters to the endpoint URL
                    var uriBuilder = new UriBuilder(endpoint);
                    var query = HttpUtility.ParseQueryString(uriBuilder.Query);
                    query["agent-id"] = agentId!;
                    query["agent-project-name"] = agentProjectName!;
                    query["agent-access-token"] = agentAccessToken;
                    uriBuilder.Query = query.ToString();
                    endpoint = uriBuilder.ToString();
                    logger.LogInformation("Agent parameters added as query parameters: agent-id={AgentId}, agent-project-name={ProjectName}", agentId, agentProjectName);
    
                    VoiceLiveClient client;
                    var endpointUri = new Uri(endpoint);
                    if (useTokenCredential)
                    {
                        var tokenCredential = new DefaultAzureCredential();
                        client = new VoiceLiveClient(endpointUri, tokenCredential, new VoiceLiveClientOptions());
                        logger.LogInformation("Using Azure token credential with agent headers");
                    }
                    else
                    {
                        var keyCredential = new Azure.AzureKeyCredential(apiKey!);
                        client = new VoiceLiveClient(endpointUri, keyCredential, new VoiceLiveClientOptions());
                        logger.LogInformation("Using API key credential with agent headers");
                    }
    
                    // Create and start voice assistant
                    using var assistant = new BasicVoiceAssistant(
                        client,
                        agentId!,
                        agentProjectName!,
                        agentAccessToken,
                        voice,
                        loggerFactory);
    
                    // Setup cancellation token for graceful shutdown
                    using var cancellationTokenSource = new CancellationTokenSource();
                    Console.CancelKeyPress += (sender, e) =>
                    {
                        e.Cancel = true;
                        logger.LogInformation("Received shutdown signal");
                        cancellationTokenSource.Cancel();
                    };
    
                    // Start the assistant
                    await assistant.StartAsync(cancellationTokenSource.Token).ConfigureAwait(false);
                }
                catch (OperationCanceledException)
                {
                    Console.WriteLine("\n👋 Voice assistant shut down. Goodbye!");
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "Fatal error");
                    Console.WriteLine($"❌ Error: {ex.Message}");
                }
            }
    
            private static bool CheckAudioSystem(ILogger logger)
            {
                try
                {
                    // Try input (default device)
                    using (var waveIn = new WaveInEvent
                    {
                        WaveFormat = new WaveFormat(24000, 16, 1),
                        BufferMilliseconds = 50
                    })
                    {
                        // Start/Stop to force initialization and surface any device errors
                        waveIn.DataAvailable += (_, __) => { };
                        waveIn.StartRecording();
                        waveIn.StopRecording();
                    }
    
                    // Try output (default device)
                    var buffer = new BufferedWaveProvider(new WaveFormat(24000, 16, 1))
                    {
                        BufferDuration = TimeSpan.FromMilliseconds(200)
                    };
    
                    using (var waveOut = new WaveOutEvent { DesiredLatency = 100 })
                    {
                        waveOut.Init(buffer);
                        // Playing isn't strictly required to validate a device, but it's safe
                        waveOut.Play();
                        waveOut.Stop();
                    }
    
                    logger.LogInformation("Audio system check passed (default input/output initialized).");
                    return true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"❌ Audio system check failed: {ex.Message}");
                    return false;
                }
            }
        }
    
        /// <summary>
        /// Basic voice assistant implementing the VoiceLive SDK patterns.
        ///</summary>
        /// <remarks>
        /// This sample now demonstrates some of the new convenience methods added to the VoiceLive SDK:
        /// - ClearStreamingAudioAsync() - Clears all input audio currently being streamed
        /// - CancelResponseAsync() - Cancels the current response generation (existing method)
        /// - ConfigureSessionAsync() - Configures session options (existing method)
        ///
        /// Additional convenience methods available but not shown in this sample:
        /// - StartAudioTurnAsync() / EndAudioTurnAsync() / CancelAudioTurnAsync() - Audio turn management
        /// - AppendAudioToTurnAsync() - Append audio data to an ongoing turn
        /// - ConnectAvatarAsync() - Connect avatar with SDP for media negotiation
        ///
        /// These methods provide a more developer-friendly API similar to the OpenAI SDK,
        /// eliminating the need to manually construct and populate ClientEvent classes.
        /// </remarks>
        public class BasicVoiceAssistant : IDisposable
        {
            private readonly VoiceLiveClient _client;
            private readonly string _agentId;
            private readonly string _agentProjectName;
            private readonly string _agentAccessToken;
            private readonly string _voice;
            private readonly ILogger<BasicVoiceAssistant> _logger;
            private readonly ILoggerFactory _loggerFactory;
    
            private VoiceLiveSession? _session;
            private AudioProcessor? _audioProcessor;
            private bool _disposed;
            // Tracks whether an assistant response is currently active (created and not yet completed)
            private bool _responseActive;
            // Tracks whether we've already sent the initial proactive greeting to start the conversation
            private bool _conversationStarted;
            // Tracks whether the assistant can still cancel the current response (between ResponseCreated and ResponseDone)
            private bool _canCancelResponse;
    
            /// <summary>
            /// Initializes a new instance of the BasicVoiceAssistant class.
            /// </summary>
            /// <param name="client">The VoiceLive client.</param>
            /// <param name="agentId">The Foundry agent ID.</param>
            /// <param name="agentProjectName">The Foundry agent project name.</param>
            /// <param name="agentAccessToken">The Foundry agent access token.</param>
            /// <param name="voice">The voice to use.</param>
            /// <param name="loggerFactory">Logger factory for creating loggers.</param>
            public BasicVoiceAssistant(
                VoiceLiveClient client,
                string agentId,
                string agentProjectName,
                string agentAccessToken,
                string voice,
                ILoggerFactory loggerFactory)
            {
                _client = client ?? throw new ArgumentNullException(nameof(client));
                _agentId = agentId ?? throw new ArgumentNullException(nameof(agentId));
                _agentProjectName = agentProjectName ?? throw new ArgumentNullException(nameof(agentProjectName));
                _agentAccessToken = agentAccessToken ?? throw new ArgumentNullException(nameof(agentAccessToken));
                _voice = voice ?? throw new ArgumentNullException(nameof(voice));
                _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
                _logger = loggerFactory.CreateLogger<BasicVoiceAssistant>();
            }
    
            /// <summary>
            /// Start the voice assistant session.
            /// </summary>
            /// <param name="cancellationToken">Cancellation token for stopping the session.</param>
            public async Task StartAsync(CancellationToken cancellationToken = default)
            {
                try
                {
                    _logger.LogInformation("Connecting to VoiceLive API with agent {AgentId} from project {ProjectName}", _agentId, _agentProjectName);
    
                    // Create session options for agent connection (no model or instructions specified)
                    var sessionOptions = await CreateSessionOptionsAsync(cancellationToken).ConfigureAwait(false);
    
                    // Start VoiceLive session with agent parameters passed via headers in client
                    _session = await _client.StartSessionAsync(sessionOptions, cancellationToken).ConfigureAwait(false);
    
                    // Initialize audio processor
                    _audioProcessor = new AudioProcessor(_session, _loggerFactory.CreateLogger<AudioProcessor>());
    
                    // Start audio systems
                    await _audioProcessor.StartPlaybackAsync().ConfigureAwait(false);
                    await _audioProcessor.StartCaptureAsync().ConfigureAwait(false);
    
                    _logger.LogInformation("Voice assistant ready! Start speaking...");
                    Console.WriteLine();
                    Console.WriteLine("=" + new string('=', 59));
                    Console.WriteLine("🎤 VOICE ASSISTANT READY");
                    Console.WriteLine("Start speaking to begin conversation");
                    Console.WriteLine("Press Ctrl+C to exit");
                    Console.WriteLine("=" + new string('=', 59));
                    Console.WriteLine();
    
                    // Process events
                    await ProcessEventsAsync(cancellationToken).ConfigureAwait(false);
                }
                catch (OperationCanceledException)
                {
                    _logger.LogInformation("Received cancellation signal, shutting down...");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Connection error");
                    throw;
                }
                finally
                {
                    // Cleanup
                    if (_audioProcessor != null)
                    {
                        await _audioProcessor.CleanupAsync().ConfigureAwait(false);
                    }
                }
            }
    
            /// <summary>
            /// Create session options for agent-based voice conversation.
            /// </summary>
            private Task<VoiceLiveSessionOptions> CreateSessionOptionsAsync(CancellationToken cancellationToken)
            {
                _logger.LogInformation("Creating voice conversation session options for agent...");
    
                // Azure voice
                var azureVoice = new AzureStandardVoice(_voice);
    
                // Create strongly typed turn detection configuration
                var turnDetectionConfig = new ServerVadTurnDetection
                {
                    Threshold = 0.5f,
                    PrefixPadding = TimeSpan.FromMilliseconds(300),
                    SilenceDuration = TimeSpan.FromMilliseconds(500)
                };
    
                // Create conversation session options for agent - no Model or Instructions specified
                // Agent parameters are passed via URI query parameters during WebSocket connection:
                // - agent-id: Agent identifier
                // - agent-project-name: Project containing the agent  
                // - agent-access-token: Generated access token for agent authentication
                var sessionOptions = new VoiceLiveSessionOptions
                {
                    InputAudioEchoCancellation = new AudioEchoCancellation(),
                    Voice = azureVoice,
                    InputAudioFormat = InputAudioFormat.Pcm16,
                    OutputAudioFormat = OutputAudioFormat.Pcm16,
                    TurnDetection = turnDetectionConfig
                };
    
                // Ensure modalities include audio
                sessionOptions.Modalities.Clear();
                sessionOptions.Modalities.Add(InteractionModality.Text);
                sessionOptions.Modalities.Add(InteractionModality.Audio);
    
                _logger.LogInformation("Session options created for agent connection");
                return Task.FromResult(sessionOptions);
            }
    
            /// <summary>
            /// Process events from the VoiceLive session.
            /// </summary>
            private async Task ProcessEventsAsync(CancellationToken cancellationToken)
            {
                try
                {
                    await foreach (SessionUpdate serverEvent in _session!.GetUpdatesAsync(cancellationToken).ConfigureAwait(false))
                    {
                        await HandleSessionUpdateAsync(serverEvent, cancellationToken).ConfigureAwait(false);
                    }
                }
                catch (OperationCanceledException)
                {
                    _logger.LogInformation("Event processing cancelled");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error processing events");
                    throw;
                }
            }
    
            /// <summary>
            /// Handle different types of server events from VoiceLive.
            /// </summary>
            private async Task HandleSessionUpdateAsync(SessionUpdate serverEvent, CancellationToken cancellationToken)
            {
                _logger.LogDebug("Received event: {EventType}", serverEvent.GetType().Name);
    
                switch (serverEvent)
                {
                    case SessionUpdateSessionCreated sessionCreated:
                        await HandleSessionCreatedAsync(sessionCreated, cancellationToken).ConfigureAwait(false);
                        break;
    
                    case SessionUpdateSessionUpdated sessionUpdated:
                        _logger.LogInformation("Session updated successfully");
    
                        // Start audio capture once session is ready
                        if (_audioProcessor != null)
                        {
                            // Proactive greeting
                            if (!_conversationStarted)
                            {
                                _conversationStarted = true;
                                _logger.LogInformation("Sending proactive greeting request");
                                try
                                {
                                    await _session!.StartResponseAsync().ConfigureAwait(false);
                                }
                                catch (Exception ex)
                                {
                                    _logger.LogError(ex, "Failed to send proactive greeting request");
                                }
                            }
                            await _audioProcessor!.StartCaptureAsync().ConfigureAwait(false);
                        }
                        break;
    
                    case SessionUpdateInputAudioBufferSpeechStarted speechStarted:
                        _logger.LogInformation("🎤 User started speaking - stopping playback");
                        Console.WriteLine("🎤 Listening...");
    
                        // Stop current assistant audio playback (interruption handling)
                        if (_audioProcessor != null)
                        {
                            await _audioProcessor.StopPlaybackAsync().ConfigureAwait(false);
                        }
    
                        // Only attempt cancellation / clearing if a response is actually active
                        if (_responseActive && _canCancelResponse)
                        {
                            // Cancel any ongoing response (only if server may still be generating)
                            try
                            {
                                await _session!.CancelResponseAsync(cancellationToken).ConfigureAwait(false);
                                _logger.LogInformation("🛑 Active response cancelled due to user barge-in");
                            }
                            catch (Exception ex)
                            {
                                // Treat known benign message as debug-level (server already finished response)
                                if (ex.Message.Contains("no active response", StringComparison.OrdinalIgnoreCase))
                                {
                                    _logger.LogDebug("Cancellation benign: response already completed");
                                }
                                else
                                {
                                    _logger.LogWarning(ex, "Response cancellation failed during barge-in");
                                }
                            }
    
                            // Clear any streaming audio still in transit only if response still marked active
                            try
                            {
                                await _session!.ClearStreamingAudioAsync(cancellationToken).ConfigureAwait(false);
                                _logger.LogInformation("✨ Cleared streaming audio after cancellation");
                            }
                            catch (Exception ex)
                            {
                                _logger.LogDebug(ex, "ClearStreamingAudio call failed (may not be supported in all scenarios)");
                            }
                        }
                        else
                        {
                            _logger.LogDebug("No active response to cancel during barge-in; skipping cancellation and clear operations");
                        }
                        break;
    
                    case SessionUpdateInputAudioBufferSpeechStopped speechStopped:
                        _logger.LogInformation("🎤 User stopped speaking");
                        Console.WriteLine("🤔 Processing...");
    
                        // Restart playback system for response
                        if (_audioProcessor != null)
                        {
                            await _audioProcessor.StartPlaybackAsync().ConfigureAwait(false);
                        }
                        break;
    
                    case SessionUpdateResponseCreated responseCreated:
                        _logger.LogInformation("🤖 Assistant response created");
                        _responseActive = true;
                        _canCancelResponse = true; // Response can be cancelled until completion
                        break;
    
                    case SessionUpdateResponseAudioDelta audioDelta:
                        // Stream audio response to speakers
                        _logger.LogDebug("Received audio delta");
    
                        if (audioDelta.Delta != null && _audioProcessor != null)
                        {
                            byte[] audioData = audioDelta.Delta.ToArray();
                            await _audioProcessor.QueueAudioAsync(audioData).ConfigureAwait(false);
                        }
                        break;
    
                    case SessionUpdateResponseAudioDone audioDone:
                        _logger.LogInformation("🤖 Assistant finished speaking");
                        Console.WriteLine("🎤 Ready for next input...");
                        // Do NOT mark _responseActive false yet; ResponseDone may still arrive
                        break;
    
                    case SessionUpdateResponseDone responseDone:
                        _logger.LogInformation("✅ Response complete");
                        _responseActive = false; // Response fully complete
                        _canCancelResponse = false; // No longer cancellable
                        break;
    
                    case SessionUpdateError errorEvent:
                        _logger.LogError("❌ VoiceLive error: {ErrorMessage}", errorEvent.Error?.Message);
                        Console.WriteLine($"Error: {errorEvent.Error?.Message}");
                        _responseActive = false;
                        _canCancelResponse = false;
                        break;
    
                    default:
                        _logger.LogDebug("Unhandled event type: {EventType}", serverEvent.GetType().Name);
                        break;
                }
            }
    
            /// <summary>
            /// Handle session created event.
            /// </summary>
            private async Task HandleSessionCreatedAsync(SessionUpdateSessionCreated sessionCreated, CancellationToken cancellationToken)
            {
                _logger.LogInformation("Session ready: {SessionId}", sessionCreated.Session?.Id);
    
                // Start audio capture once session is ready
                if (_audioProcessor != null)
                {
                    await _audioProcessor.StartCaptureAsync().ConfigureAwait(false);
                }
            }
    
            /// <summary>
            /// Dispose of resources.
            /// </summary>
            public void Dispose()
            {
                if (_disposed)
                    return;
    
                _audioProcessor?.Dispose();
                _session?.Dispose();
                _disposed = true;
            }
        }
    
        /// <summary>
        /// Handles real-time audio capture and playback for the voice assistant.
        ///
        /// This processor demonstrates some of the new VoiceLive SDK convenience methods:
        /// - Uses existing SendInputAudioAsync() method for audio streaming
        /// - Shows how convenience methods simplify audio operations
        ///
        /// Additional convenience methods available in the SDK:
        /// - StartAudioTurnAsync() / AppendAudioToTurnAsync() / EndAudioTurnAsync() - Audio turn management
        /// - ClearStreamingAudioAsync() - Clear all streaming audio
        /// - ConnectAvatarAsync() - Avatar connection with SDP
        ///
        /// Threading Architecture:
        /// - Main thread: Event loop and UI
        /// - Capture thread: NAudio input stream reading
        /// - Send thread: Async audio data transmission to VoiceLive
        /// - Playback thread: NAudio output stream writing
        /// </summary>
        public class AudioProcessor : IDisposable
        {
            private readonly VoiceLiveSession _session;
            private readonly ILogger<AudioProcessor> _logger;
    
            // Audio configuration - PCM16, 24kHz, mono as specified
            private const int SampleRate = 24000;
            private const int Channels = 1;
            private const int BitsPerSample = 16;
    
            // NAudio components
            private WaveInEvent? _waveIn;
            private WaveOutEvent? _waveOut;
            private BufferedWaveProvider? _playbackBuffer;
    
            // Audio capture and playback state
            private bool _isCapturing;
            private bool _isPlaying;
    
            // Audio streaming channels
            private readonly Channel<byte[]> _audioSendChannel;
            private readonly Channel<byte[]> _audioPlaybackChannel;
            private readonly ChannelWriter<byte[]> _audioSendWriter;
            private readonly ChannelReader<byte[]> _audioSendReader;
            private readonly ChannelWriter<byte[]> _audioPlaybackWriter;
            private readonly ChannelReader<byte[]> _audioPlaybackReader;
    
            // Background tasks
            private Task? _audioSendTask;
            private Task? _audioPlaybackTask;
            private readonly CancellationTokenSource _cancellationTokenSource;
            private CancellationTokenSource _playbackCancellationTokenSource;
    
            /// <summary>
            /// Initializes a new instance of the AudioProcessor class.
            /// </summary>
            /// <param name="session">The VoiceLive session for audio communication.</param>
            /// <param name="logger">Logger for diagnostic information.</param>
            public AudioProcessor(VoiceLiveSession session, ILogger<AudioProcessor> logger)
            {
                _session = session ?? throw new ArgumentNullException(nameof(session));
                _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    
                // Create unbounded channels for audio data
                _audioSendChannel = Channel.CreateUnbounded<byte[]>();
                _audioSendWriter = _audioSendChannel.Writer;
                _audioSendReader = _audioSendChannel.Reader;
    
                _audioPlaybackChannel = Channel.CreateUnbounded<byte[]>();
                _audioPlaybackWriter = _audioPlaybackChannel.Writer;
                _audioPlaybackReader = _audioPlaybackChannel.Reader;
    
                _cancellationTokenSource = new CancellationTokenSource();
                _playbackCancellationTokenSource = new CancellationTokenSource();
    
                _logger.LogInformation("AudioProcessor initialized with {SampleRate}Hz PCM16 mono audio", SampleRate);
            }
    
            /// <summary>
            /// Start capturing audio from microphone.
            /// </summary>
            public Task StartCaptureAsync()
            {
                if (_isCapturing)
                    return Task.CompletedTask;
    
                _isCapturing = true;
    
                try
                {
                    _waveIn = new WaveInEvent
                    {
                        WaveFormat = new WaveFormat(SampleRate, BitsPerSample, Channels),
                        BufferMilliseconds = 50 // 50ms buffer for low latency
                    };
    
                    _waveIn.DataAvailable += OnAudioDataAvailable;
                    _waveIn.RecordingStopped += OnRecordingStopped;
    
                    _waveIn.DeviceNumber = 0;
    
                    _waveIn.StartRecording();
    
                    // Start audio send task
                    _audioSendTask = ProcessAudioSendAsync(_cancellationTokenSource.Token);
    
                    _logger.LogInformation("Started audio capture");
                    return Task.CompletedTask;
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Failed to start audio capture");
                    _isCapturing = false;
                    throw;
                }
            }
    
            /// <summary>
            /// Stop capturing audio.
            /// </summary>
            public async Task StopCaptureAsync()
            {
                if (!_isCapturing)
                    return;
    
                _isCapturing = false;
    
                if (_waveIn != null)
                {
                    _waveIn.StopRecording();
                    _waveIn.DataAvailable -= OnAudioDataAvailable;
                    _waveIn.RecordingStopped -= OnRecordingStopped;
                    _waveIn.Dispose();
                    _waveIn = null;
                }
    
                // Complete the send channel and wait for the send task
                _audioSendWriter.TryComplete();
                if (_audioSendTask != null)
                {
                    await _audioSendTask.ConfigureAwait(false);
                    _audioSendTask = null;
                }
    
                _logger.LogInformation("Stopped audio capture");
            }
    
            /// <summary>
            /// Initialize audio playback system.
            /// </summary>
            public Task StartPlaybackAsync()
            {
                if (_isPlaying)
                    return Task.CompletedTask;
    
                _isPlaying = true;
    
                try
                {
                    _waveOut = new WaveOutEvent
                    {
                        DesiredLatency = 100 // 100ms latency
                    };
    
                    _playbackBuffer = new BufferedWaveProvider(new WaveFormat(SampleRate, BitsPerSample, Channels))
                    {
                        BufferDuration = TimeSpan.FromSeconds(10), // 10 second buffer
                        DiscardOnBufferOverflow = true
                    };
    
                    _waveOut.Init(_playbackBuffer);
                    _waveOut.Play();
    
                    _playbackCancellationTokenSource = new CancellationTokenSource();
    
                    // Start audio playback task
                    _audioPlaybackTask = ProcessAudioPlaybackAsync();
    
                    _logger.LogInformation("Audio playback system ready");
                    return Task.CompletedTask;
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Failed to initialize audio playback");
                    _isPlaying = false;
                    throw;
                }
            }
    
            /// <summary>
            /// Stop audio playback and clear buffer.
            /// </summary>
            public async Task StopPlaybackAsync()
            {
                if (!_isPlaying)
                    return;
    
                _isPlaying = false;
    
                // Clear the playback channel
                while (_audioPlaybackReader.TryRead(out _))
                { }
    
                if (_playbackBuffer != null)
                {
                    _playbackBuffer.ClearBuffer();
                }
    
                if (_waveOut != null)
                {
                    _waveOut.Stop();
                    _waveOut.Dispose();
                    _waveOut = null;
                }
    
                _playbackBuffer = null;
    
                // Complete the playback channel and wait for the playback task
                _playbackCancellationTokenSource.Cancel();
    
                if (_audioPlaybackTask != null)
                {
                    await _audioPlaybackTask.ConfigureAwait(false);
                    _audioPlaybackTask = null;
                }
    
                _logger.LogInformation("Stopped audio playback");
            }
    
            /// <summary>
            /// Queue audio data for playback.
            /// </summary>
            /// <param name="audioData">The audio data to queue.</param>
            public async Task QueueAudioAsync(byte[] audioData)
            {
                if (_isPlaying && audioData.Length > 0)
                {
                    await _audioPlaybackWriter.WriteAsync(audioData).ConfigureAwait(false);
                }
            }
    
            /// <summary>
            /// Event handler for audio data available from microphone.
            /// </summary>
            private void OnAudioDataAvailable(object? sender, WaveInEventArgs e)
            {
                if (_isCapturing && e.BytesRecorded > 0)
                {
                    byte[] audioData = new byte[e.BytesRecorded];
                    Array.Copy(e.Buffer, 0, audioData, 0, e.BytesRecorded);
    
                    // Queue audio data for sending (non-blocking)
                    if (!_audioSendWriter.TryWrite(audioData))
                    {
                        _logger.LogWarning("Failed to queue audio data for sending - channel may be full");
                    }
                }
            }
    
            /// <summary>
            /// Event handler for recording stopped.
            /// </summary>
            private void OnRecordingStopped(object? sender, StoppedEventArgs e)
            {
                if (e.Exception != null)
                {
                    _logger.LogError(e.Exception, "Audio recording stopped due to error");
                }
            }
    
            /// <summary>
            /// Background task to process audio data and send to VoiceLive service.
            /// </summary>
            private async Task ProcessAudioSendAsync(CancellationToken cancellationToken)
            {
                try
                {
                    await foreach (byte[] audioData in _audioSendReader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
                    {
                        if (cancellationToken.IsCancellationRequested)
                            break;
    
                        try
                        {
                            // Send audio data directly to the session using the convenience method
                            // This demonstrates the existing SendInputAudioAsync convenience method
                            // Other available methods: StartAudioTurnAsync, AppendAudioToTurnAsync, EndAudioTurnAsync
                            await _session.SendInputAudioAsync(audioData, cancellationToken).ConfigureAwait(false);
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex, "Error sending audio data to VoiceLive");
                            // Continue processing other audio data
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    // Expected when cancellation is requested
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error in audio send processing");
                }
            }
    
            /// <summary>
            /// Background task to process audio playback.
            /// </summary>
            private async Task ProcessAudioPlaybackAsync()
            {
                try
                {
                    CancellationTokenSource combinedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_playbackCancellationTokenSource.Token, _cancellationTokenSource.Token);
                    var cancellationToken = combinedTokenSource.Token;
    
                    await foreach (byte[] audioData in _audioPlaybackReader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
                    {
                        if (cancellationToken.IsCancellationRequested)
                            break;
    
                        try
                        {
                            if (_playbackBuffer != null && _isPlaying)
                            {
                                _playbackBuffer.AddSamples(audioData, 0, audioData.Length);
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex, "Error in audio playback");
                            // Continue processing other audio data
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    // Expected when cancellation is requested
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error in audio playback processing");
                }
            }
    
            /// <summary>
            /// Clean up audio resources.
            /// </summary>
            public async Task CleanupAsync()
            {
                await StopCaptureAsync().ConfigureAwait(false);
                await StopPlaybackAsync().ConfigureAwait(false);
    
                _cancellationTokenSource.Cancel();
    
                // Wait for background tasks to complete
                var tasks = new List<Task>();
                if (_audioSendTask != null)
                    tasks.Add(_audioSendTask);
                if (_audioPlaybackTask != null)
                    tasks.Add(_audioPlaybackTask);
    
                if (tasks.Count > 0)
                {
                    await Task.WhenAll(tasks).ConfigureAwait(false);
                }
    
                _logger.LogInformation("Audio processor cleaned up");
            }
    
            /// <summary>
            /// Dispose of resources.
            /// </summary>
            public void Dispose()
            {
                CleanupAsync().Wait();
                _cancellationTokenSource.Dispose();
            }
        }
    }
    
  6. Ejecute la aplicación de consola para iniciar la conversación en directo:

    dotnet run
    

Salida

La salida del script se imprime en la consola. Verá mensajes que indican el estado de la conexión, la secuencia de audio y la reproducción. El audio se reproduce a través de los altavoces o auriculares.

info: Azure.AI.VoiceLive.Samples.Program[0]
      Generating agent access token using DefaultAzureCredential...
info: Azure.AI.VoiceLive.Samples.Program[0]
      Obtained agent access token successfully
info: Azure.AI.VoiceLive.Samples.Program[0]
      Audio system check passed (default input/output initialized).
info: Azure.AI.VoiceLive.Samples.Program[0]
      Agent parameters added as query parameters: agent-id=asst_my-agent, agent-project-name=my-ai-project
info: Azure.AI.VoiceLive.Samples.Program[0]
      Using Azure token credential with agent headers
info: Azure.AI.VoiceLive.Samples.BasicVoiceAssistant[0]
      Connecting to VoiceLive API with agent asst_my-agent from project my-ai-project
info: Azure.AI.VoiceLive.Samples.BasicVoiceAssistant[0]
      Creating voice conversation session options for agent...
info: Azure.AI.VoiceLive.Samples.BasicVoiceAssistant[0]
      Session options created for agent connection
info: Azure.AI.VoiceLive.Samples.AudioProcessor[0]
      AudioProcessor initialized with 24000Hz PCM16 mono audio
info: Azure.AI.VoiceLive.Samples.AudioProcessor[0]
      Audio playback system ready
info: Azure.AI.VoiceLive.Samples.AudioProcessor[0]
      Started audio capture
info: Azure.AI.VoiceLive.Samples.BasicVoiceAssistant[0]
      Voice assistant ready! Start speaking...

============================================================
🎤 VOICE ASSISTANT READY
Start speaking to begin conversation
Press Ctrl+C to exit
============================================================

info: Azure.AI.VoiceLive.Samples.BasicVoiceAssistant[0]
      Session ready: sess_QNwzS5xxxxQjftd
info: Azure.AI.VoiceLive.Samples.BasicVoiceAssistant[0]
      Session updated successfully
🎤 Listening...
info: Azure.AI.VoiceLive.Samples.BasicVoiceAssistant[0]
      🎤 User started speaking - stopping playback
info: Azure.AI.VoiceLive.Samples.AudioProcessor[0]
      Stopped audio playback
info: Azure.AI.VoiceLive.Samples.BasicVoiceAssistant[0]
      ✨ Used ClearStreamingAudioAsync convenience method
🎤 Ready for next input...
info: Azure.AI.VoiceLive.Samples.BasicVoiceAssistant[0]
      🤖 Assistant finished speaking
info: Azure.AI.VoiceLive.Samples.BasicVoiceAssistant[0]
      ✅ Response complete
🤔 Processing...
info: Azure.AI.VoiceLive.Samples.BasicVoiceAssistant[0]
      🎤 User stopped speaking
info: Azure.AI.VoiceLive.Samples.AudioProcessor[0]
      Audio playback system ready
info: Azure.AI.VoiceLive.Samples.BasicVoiceAssistant[0]
      🤖 Assistant response created
🎤 Ready for next input...
info: Azure.AI.VoiceLive.Samples.BasicVoiceAssistant[0]
      🤖 Assistant finished speaking
info: Azure.AI.VoiceLive.Samples.BasicVoiceAssistant[0]
      ✅ Response complete
info: Azure.AI.VoiceLive.Samples.Program[0]
      Received shutdown signal
info: Azure.AI.VoiceLive.Samples.BasicVoiceAssistant[0]
      Event processing cancelled
info: Azure.AI.VoiceLive.Samples.AudioProcessor[0]
      Stopped audio capture
info: Azure.AI.VoiceLive.Samples.AudioProcessor[0]
      Stopped audio playback
info: Azure.AI.VoiceLive.Samples.AudioProcessor[0]
      Audio processor cleaned up
info: Azure.AI.VoiceLive.Samples.AudioProcessor[0]
      Audio processor cleaned up