### Initialize and Start Servers (Bash) Source: https://github.com/deepgram-starters/cpp-live-text-to-speech/blob/main/AGENTS.md Quick start commands to initialize the project, set up environment variables, and start both the backend and frontend servers. ```bash # Initialize (clone submodules + install deps) make init # Set up environment test -f .env || cp sample.env .env # then set DEEPGRAM_API_KEY # Start both servers make start # Backend: http://localhost:8081 # Frontend: http://localhost:8080 ``` -------------------------------- ### Start Servers Separately (Bash) Source: https://github.com/deepgram-starters/cpp-live-text-to-speech/blob/main/AGENTS.md Instructions to start the backend and frontend servers in separate terminals. ```bash # Terminal 1 — Backend ./build/app # Terminal 2 — Frontend cd frontend && corepack pnpm run dev -- --port 8080 --no-open ``` -------------------------------- ### Frontend Dependencies Installation (Bash) Source: https://github.com/deepgram-starters/cpp-live-text-to-speech/blob/main/AGENTS.md Command to install frontend Node.js dependencies using pnpm. ```bash cd frontend && corepack pnpm install ``` -------------------------------- ### Backend Dependencies Installation (Bash) Source: https://github.com/deepgram-starters/cpp-live-text-to-speech/blob/main/AGENTS.md Command to install backend C++ dependencies using CMake and vcpkg. Ensure the VCPKG_ROOT environment variable is set. ```bash cmake -B build -S . -DCMAKE_TOOLCHAIN_FILE="$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" && cmake --build build ``` -------------------------------- ### Initialize and Run the C++ Project Source: https://github.com/deepgram-starters/cpp-live-text-to-speech/blob/main/README.md Use these commands to prepare the environment and start the application. Ensure the DEEPGRAM_API_KEY is configured in the .env file before running. ```bash make init cp sample.env .env # Add your DEEPGRAM_API_KEY make start ``` -------------------------------- ### Conventional Commit Examples Source: https://github.com/deepgram-starters/cpp-live-text-to-speech/blob/main/AGENTS.md Standardized commit message formats for project contributions. ```text feat(cpp-live-text-to-speech): add diarization support fix(cpp-live-text-to-speech): resolve WebSocket close handling refactor(cpp-live-text-to-speech): simplify session endpoint chore(deps): update frontend submodule ``` -------------------------------- ### GET /api/metadata Source: https://context7.com/deepgram-starters/cpp-live-text-to-speech/llms.txt Retrieves project configuration details including the framework, language, and supported use cases. ```APIDOC ## GET /api/metadata ### Description Returns project metadata from the deepgram.toml configuration file including the use case, framework, language, and other project details. ### Method GET ### Endpoint /api/metadata ### Response #### Success Response (200) - **title** (string) - Project title - **description** (string) - Project description - **author** (string) - Author information - **repository** (string) - GitHub repository URL - **useCase** (string) - Primary use case - **language** (string) - Programming language - **framework** (string) - Web framework used - **sdk** (string) - SDK information - **tags** (array) - List of relevant tags #### Response Example { "title": "C++ Live Text-to-Speech Starter", "description": "Get started using Deepgram's Live Text-to-Speech with this C++ demo app", "author": "Deepgram DX Team (https://developers.deepgram.com)", "repository": "https://github.com/deepgram-starters/cpp-live-text-to-speech", "useCase": "live-text-to-speech", "language": "cpp", "framework": "Crow", "sdk": "N/A", "tags": ["live-text-to-speech", "live-tts", "streaming-tts", "real-time-tts"] } ``` -------------------------------- ### Build and Development Commands Source: https://context7.com/deepgram-starters/cpp-live-text-to-speech/llms.txt Utilize the Makefile for common development tasks such as checking prerequisites, initializing the project, starting development servers, building for production, running tests, updating submodules, and cleaning build artifacts. ```bash # Check prerequisites (git, cmake, pnpm) make check-prereqs ``` ```bash # Initialize project: clone submodules and install all dependencies make init ``` ```bash # Start both backend and frontend development servers make start # Backend: http://localhost:8081 # Frontend: http://localhost:8080 ``` ```bash # Start servers individually make start-backend # C++ backend only on port 8081 make start-frontend # Vite frontend only on port 8080 ``` ```bash # Build frontend for production make build ``` ```bash # Run contract conformance tests (requires running server) make test ``` ```bash # Update git submodules to latest commits make update ``` ```bash # Clean all build artifacts make clean ``` -------------------------------- ### GET /health Source: https://context7.com/deepgram-starters/cpp-live-text-to-speech/llms.txt A simple health check endpoint to verify that the server is running and accepting connections. ```APIDOC ## GET /health ### Description Simple health check endpoint that returns HTTP 200 OK when the server is running and accepting connections. ### Method GET ### Endpoint /health ### Response #### Success Response (200) - **status** (string) - OK ``` -------------------------------- ### WebSocket Message Protocol (JSON) Source: https://github.com/deepgram-starters/cpp-live-text-to-speech/blob/main/AGENTS.md Examples of JSON messages used for client-server communication over the WebSocket for text-to-speech synthesis. ```json { "type": "Speak", "text": "Hello world" } ``` ```json { "type": "Flush" } ``` ```json { "type": "Clear" } ``` ```json { "type": "Close" } ``` -------------------------------- ### GET /api/session Source: https://context7.com/deepgram-starters/cpp-live-text-to-speech/llms.txt Issues a signed JWT token required for authenticating WebSocket connections to the live TTS endpoint. The token is valid for one hour. ```APIDOC ## GET /api/session ### Description Issues a signed JWT token for WebSocket authentication. The token expires after 1 hour and must be passed as a WebSocket subprotocol when connecting to the live TTS endpoint. ### Method GET ### Endpoint /api/session ### Response #### Success Response (200) - **token** (string) - The signed JWT token for authentication. #### Response Example { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." } ``` -------------------------------- ### WebSocket Message Protocol for TTS Source: https://context7.com/deepgram-starters/cpp-live-text-to-speech/llms.txt Use these JSON messages to control audio synthesis via WebSocket. Text is queued for synthesis and audio is streamed back as binary frames. The `synthesizeSpeech` function provides a complete workflow example. ```javascript // Speak - Queue text for synthesis ws.send(JSON.stringify({ type: 'Speak', text: 'Convert this text to speech audio.' })); ``` ```javascript // Flush - Signal end of text and flush the audio buffer // Use after sending all Speak messages to ensure complete audio delivery ws.send(JSON.stringify({ type: 'Flush' })); ``` ```javascript // Clear - Cancel any pending audio in the synthesis queue ws.send(JSON.stringify({ type: 'Clear' })); ``` ```javascript // Close - Gracefully disconnect from the TTS session ws.send(JSON.stringify({ type: 'Close' })); ``` ```javascript // Example: Complete synthesis workflow async function synthesizeSpeech(text) { return new Promise((resolve, reject) => { const audioChunks = []; ws.onmessage = (event) => { if (event.data instanceof ArrayBuffer) { audioChunks.push(new Int16Array(event.data)); } }; ws.onclose = () => { // Combine all audio chunks const totalLength = audioChunks.reduce((sum, chunk) => sum + chunk.length, 0); const combined = new Int16Array(totalLength); let offset = 0; for (const chunk of audioChunks) { combined.set(chunk, offset); offset += chunk.length; } resolve(combined); }; ws.send(JSON.stringify({ type: 'Speak', text })); ws.send(JSON.stringify({ type: 'Flush' })); }); } ``` -------------------------------- ### Build and Run Configuration Source: https://context7.com/deepgram-starters/cpp-live-text-to-speech/llms.txt Configure, build, and execute the C++ backend using CMake and vcpkg. ```bash # Ensure VCPKG_ROOT environment variable is set export VCPKG_ROOT=/path/to/vcpkg # Configure the build with vcpkg toolchain cmake -B build -S . -DCMAKE_TOOLCHAIN_FILE=$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake # Build the project cmake --build build # Run the compiled binary ./build/cpp-live-text-to-speech ``` -------------------------------- ### Environment Configuration Source: https://context7.com/deepgram-starters/cpp-live-text-to-speech/llms.txt Configure the backend server by creating a `.env` file. This file should contain your Deepgram API key and optionally specify the server port, bind address, and JWT signing secret. ```bash # Copy the sample environment file cp sample.env .env # Required: Add your Deepgram API key # Get your API key from https://console.deepgram.com DEEPGRAM_API_KEY=your_deepgram_api_key_here # Optional: Backend server port (default: 8081) PORT=8081 # Optional: Server bind address (default: 0.0.0.0) HOST=0.0.0.0 # Optional: JWT signing secret for production # If not set, a random secret is generated on each server start SESSION_SECRET=your_secure_random_secret_here # Verify configuration by starting the server make start-backend ``` -------------------------------- ### Project Testing Commands Source: https://github.com/deepgram-starters/cpp-live-text-to-speech/blob/main/AGENTS.md Commands for running conformance tests and verifying API endpoints. ```bash # Run conformance tests (requires app to be running) make test # Manual endpoint check curl -sf http://localhost:8081/api/metadata | python3 -m json.tool curl -sf http://localhost:8081/api/session | python3 -m json.tool ``` -------------------------------- ### Configure C++ Project with CMake Source: https://github.com/deepgram-starters/cpp-live-text-to-speech/blob/main/CMakeLists.txt Sets up the CMake build system for a C++ project, specifying the minimum required version, project name, and C++ standard. It also finds and links essential dependencies. ```cmake cmake_minimum_required(VERSION 3.20) project(cpp-live-text-to-speech LANGUAGES CXX) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) # Find dependencies installed via vcpkg find_package(Crow CONFIG REQUIRED) find_package(Boost REQUIRED COMPONENTS system) find_package(OpenSSL REQUIRED) find_package(toml11 CONFIG REQUIRED) find_package(jwt-cpp CONFIG REQUIRED) add_executable(${PROJECT_NAME} src/main.cpp) target_link_libraries(${PROJECT_NAME} PRIVATE Crow::Crow Boost::system OpenSSL::SSL OpenSSL::Crypto toml11::toml11 jwt-cpp::jwt-cpp ) ``` -------------------------------- ### Project Management Commands Source: https://context7.com/deepgram-starters/cpp-live-text-to-speech/llms.txt Use these commands to check submodule status or eject the frontend directory. ```bash make status ``` ```bash make eject-frontend ``` -------------------------------- ### Fetch Project Metadata Source: https://context7.com/deepgram-starters/cpp-live-text-to-speech/llms.txt Retrieve project metadata including use case, framework, and language from the `deepgram.toml` configuration file. ```bash # Fetch project metadata curl -s http://localhost:8081/api/metadata | python3 -m json.tool ``` -------------------------------- ### Voice Models and Audio Configuration Source: https://context7.com/deepgram-starters/cpp-live-text-to-speech/llms.txt Configure voice models and audio output formats using URLSearchParams when establishing the WebSocket connection. Available options for models, encoding, sample rates, and container formats are listed. ```javascript // Available voice models (Aura family) const voiceModels = [ 'aura-asteria-en', // Default English female voice 'aura-luna-en', // English female voice 'aura-stella-en', // English female voice 'aura-athena-en', // English female voice 'aura-hera-en', // English female voice 'aura-orion-en', // English male voice 'aura-arcas-en', // English male voice 'aura-perseus-en', // English male voice 'aura-angus-en', // English male voice 'aura-orpheus-en', // English male voice 'aura-helios-en', // English male voice 'aura-zeus-en' // English male voice ]; ``` ```javascript // Audio encoding options const encodingOptions = { 'linear16': 'Raw PCM 16-bit signed integers (default)', 'mp3': 'MP3 compressed audio', 'opus': 'Opus compressed audio', 'mulaw': 'μ-law encoded audio (telephony)', 'alaw': 'A-law encoded audio (telephony)' }; ``` ```javascript // Sample rate options (Hz) const sampleRates = [8000, 16000, 22050, 24000, 32000, 44100, 48000]; ``` ```javascript // Container format options const containerFormats = { 'none': 'Raw audio stream (default)', 'wav': 'WAV container with headers', 'ogg': 'OGG container' }; ``` ```javascript // Example: High-quality audio configuration const highQualityParams = new URLSearchParams({ model: 'aura-orion-en', encoding: 'linear16', sample_rate: '48000', container: 'none' }); ``` ```javascript // Example: Telephony-optimized configuration const telephonyParams = new URLSearchParams({ model: 'aura-asteria-en', encoding: 'mulaw', sample_rate: '8000', container: 'none' }); ``` ```javascript const ws = new WebSocket( `ws://localhost:8081/api/live-text-to-speech?${highQualityParams}`, [`access_token.${token}`] ); ``` -------------------------------- ### Stop Servers (Bash) Source: https://github.com/deepgram-starters/cpp-live-text-to-speech/blob/main/AGENTS.md Command to stop the backend and frontend servers by finding and killing their processes. ```bash lsof -ti:8080,8081 | xargs kill -9 2>/dev/null ``` -------------------------------- ### WS /api/live-text-to-speech Source: https://context7.com/deepgram-starters/cpp-live-text-to-speech/llms.txt WebSocket endpoint for real-time text-to-speech synthesis. Requires JWT authentication via subprotocol and supports streaming binary audio data. ```APIDOC ## WS /api/live-text-to-speech ### Description WebSocket endpoint that proxies messages to Deepgram's Live TTS API. Requires JWT authentication via the access_token. subprotocol. Accepts JSON control messages and streams back binary audio data. ### Method WS ### Endpoint /api/live-text-to-speech ### Query Parameters - **model** (string) - Optional - Voice model (e.g., aura-asteria-en) - **encoding** (string) - Optional - Audio encoding (linear16, mp3, opus, mulaw, alaw) - **sample_rate** (string) - Optional - Sample rate (8000-48000) - **container** (string) - Optional - Container format (none, wav, ogg) ### Request Body - **type** (string) - Required - Control message type (e.g., 'Speak', 'Flush') - **text** (string) - Optional - Text content for synthesis ``` -------------------------------- ### Clean Rebuild (Bash) Source: https://github.com/deepgram-starters/cpp-live-text-to-speech/blob/main/AGENTS.md Commands to perform a clean rebuild of the project, including removing build artifacts and reinstalling dependencies. ```bash rm -rf build frontend/node_modules frontend/.vite make init ``` -------------------------------- ### Frontend Git Submodule Update Workflow (Bash) Source: https://github.com/deepgram-starters/cpp-live-text-to-speech/blob/main/AGENTS.md Steps to modify the frontend code, commit changes within the submodule, push them, and then update the main project's submodule reference. ```bash cd frontend && git add . && git commit -m "feat: description" cd frontend && git push origin main cd .. && git add frontend && git commit -m "chore(deps): update frontend submodule" ``` -------------------------------- ### Establish WebSocket Connection for Live TTS Source: https://context7.com/deepgram-starters/cpp-live-text-to-speech/llms.txt Connect to the real-time text-to-speech WebSocket endpoint using JWT authentication. Configure TTS parameters like voice model, encoding, and sample rate. ```javascript // Frontend WebSocket connection with authentication const sessionResponse = await fetch('/api/session'); const { token } = await sessionResponse.json(); // Connect with JWT token as subprotocol and optional TTS parameters const params = new URLSearchParams({ model: 'aura-asteria-en', // Voice model encoding: 'linear16', // Audio encoding: linear16, mp3, opus, mulaw, alaw sample_rate: '48000', // Sample rate: 8000-48000 container: 'none' // Container format: none, wav, ogg }); const ws = new WebSocket( `ws://localhost:8081/api/live-text-to-speech?${params}`, [`access_token.${token}`] // JWT auth via subprotocol ); // Handle binary audio data from Deepgram ws.binaryType = 'arraybuffer'; ws.onmessage = (event) => { if (event.data instanceof ArrayBuffer) { // Raw PCM Int16 audio data - convert to Float32 for Web Audio API const int16Data = new Int16Array(event.data); const float32Data = new Float32Array(int16Data.length); for (let i = 0; i < int16Data.length; i++) { float32Data[i] = int16Data[i] / 32768.0; } // Queue audio for playback... } else { // JSON control messages from Deepgram const message = JSON.parse(event.data); console.log('Control message:', message); } }; // Send text for synthesis ws.onopen = () => { // Queue text for audio generation ws.send(JSON.stringify({ type: 'Speak', text: 'Hello, world!' })); ws.send(JSON.stringify({ type: 'Speak', text: 'This is real-time text-to-speech.' })); // Flush the buffer to signal end of text ws.send(JSON.stringify({ type: 'Flush' })); }; // Handle connection close ws.onclose = (event) => { console.log('WebSocket closed:', event.reason); }; ``` -------------------------------- ### Check Server Health Source: https://context7.com/deepgram-starters/cpp-live-text-to-speech/llms.txt Perform a health check on the server to ensure it is running and accepting connections. Returns HTTP 200 OK. ```bash # Check server health curl -s -w "\nHTTP Status: %{http_code}\n" http://localhost:8081/health ``` ```bash # Use in container orchestration or load balancer health checks curl -sf http://localhost:8081/health && echo "Server is healthy" || echo "Server is down" ``` -------------------------------- ### Request JWT Session Token Source: https://context7.com/deepgram-starters/cpp-live-text-to-speech/llms.txt Obtain a signed JWT token for WebSocket authentication. The token expires after 1 hour and must be passed as a WebSocket subprotocol. ```bash # Request a session token curl -s http://localhost:8081/api/session | python3 -m json.tool ``` ```bash # Store the token for WebSocket connections TOKEN=$(curl -s http://localhost:8081/api/session | jq -r '.token') echo "Session token: $TOKEN" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.