### curl: Text-to-Speech API Examples Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt This section provides curl commands for interacting with a TTS API. It includes examples for synthesizing speech and saving it to a file, listing available voices, synthesizing speech with specific voice and speed settings, and performing a health check. An API key is required for all operations. ```bash API_KEY="YOUR_KEY" BASE="https://apim-ai-apis.azure-api.net/v1/tts" # Synthesize speech (output to file) curl -X POST "$BASE/synthesize" \ -H "Content-Type: application/json" \ -H "Ocp-Apim-Subscription-Key: $API_KEY" \ -d '{"text": "Hello world, this is a text to speech test.", "voice": "af_heart", "speed": 1.0}' \ --output output.wav # List available voices curl -s "$BASE/voices" \ -H "Ocp-Apim-Subscription-Key: $API_KEY" | python3 -m json.tool # British male voice at slow speed curl -X POST "$BASE/synthesize" \ -H "Content-Type: application/json" \ -H "Ocp-Apim-Subscription-Key: $API_KEY" \ -d '{"text": "The weather in London is quite pleasant today.", "voice": "bm_george", "speed": 0.8}' \ --output british_slow.wav # Health check curl -s "$BASE/health" \ -H "Ocp-Apim-Subscription-Key: $API_KEY" | python3 -m json.tool ``` -------------------------------- ### Python: LangChain TTS Tool Integration for Agents Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt This example shows how to integrate TTS functionality into a LangChain agent by defining custom tools for text-to-speech conversion and listing available voices. It utilizes 'langchain_core', 'langchain_brainiall', and 'langgraph'. The output includes base64-encoded audio data and duration information, or a list of available voices. ```python from langchain_core.tools import tool from langchain_brainiall import ChatBrainiall from langgraph.prebuilt import create_react_agent import requests import base64 API_KEY = "YOUR_KEY" TTS_URL = "https://apim-ai-apis.azure-api.net/v1/tts" @tool def text_to_speech(text: str, voice: str = "af_heart", speed: float = 1.0) -> str: """Convert text to speech audio. Returns base64-encoded WAV audio. Available voices: af_heart (warm female), bf_emma (British female), am_michael (professional male), bm_george (British male narrator). Speed range: 0.25 (very slow) to 4.0 (very fast).""" response = requests.post( f"{TTS_URL}/synthesize", headers={"Ocp-Apim-Subscription-Key": API_KEY}, json={"text": text, "voice": voice, "speed": speed}, ) response.raise_for_status() audio_b64 = base64.b64encode(response.content).decode() duration = response.headers.get("X-Audio-Duration-Ms", "?") return f"Audio generated: {duration}ms, {len(response.content)} bytes. Base64: {audio_b64[:50]}..." @tool def list_tts_voices() -> str: """List all available text-to-speech voices with their accents and genders.""" response = requests.get( f"{TTS_URL}/voices", headers={"Ocp-Apim-Subscription-Key": API_KEY}, ) voices = response.json()["voices"] return "\n".join(f"{v['id']}: {v['name']} ({v['gender']}, {v['accent']})" for v in voices) # Create agent with TTS capabilities llm = ChatBrainiall(model="claude-sonnet-4-6", api_key=API_KEY) agent = create_react_agent(llm, [text_to_speech, list_tts_voices]) result = agent.invoke({ "messages": [("human", "List available British voices, then synthesize 'Good morning' with the best male British voice") ] }) for msg in result["messages"]: if msg.content: print(f"{msg.type}: {msg.content[:200]}") ``` -------------------------------- ### Migrate from ElevenLabs to Brainiall TTS with Python Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt Compares and demonstrates the migration from ElevenLabs TTS API to the Azure AI TTS API (referred to as Brainiall in the example). It highlights differences in endpoint structure, parameters, and cost. Requires the 'requests' library. ```python # BEFORE: ElevenLabs ($0.18/1K chars) import requests response = requests.post( "https://api.elevenlabs.io/v1/text-to-speech/21m00Tcm4TlvDq8ikWAM", headers={ "xi-api-key": "YOUR_ELEVEN_KEY", "Content-Type": "application/json", }, json={ "text": "Hello world", "model_id": "eleven_turbo_v2_5", "voice_settings": {"stability": 0.5, "similarity_boost": 0.75}, }, ) audio = response.content # AFTER: Brainiall ($0.01-0.03/1K chars) — 6-18x cheaper response = requests.post( "https://apim-ai-apis.azure-api.net/v1/tts/synthesize", headers={"Ocp-Apim-Subscription-Key": "YOUR_KEY"}, json={"text": "Hello world", "voice": "af_heart", "speed": 1.0}, ) audio = response.content ``` -------------------------------- ### TTS Synthesis with Voice Selection Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt Provides examples of synthesizing speech using different voices and speeds, demonstrating how to select specific accents and genders for audio output. ```APIDOC ## POST /v1/tts/synthesize ### Description Synthesizes text to speech audio, allowing for specific voice selection based on gender and accent, as well as adjusting speech speed for different use cases like narration or language learning. ### Method POST ### Endpoint https://apim-ai-apis.azure-api.net/v1/tts/synthesize ### Parameters #### Headers - **Ocp-Apim-Subscription-Key** (string) - Required - Your API subscription key. #### Request Body - **text** (string) - Required - The text to convert to speech. - **voice** (string) - Optional - The specific voice ID to use (e.g., "af_heart" for American Female, "bm_george" for British Male). - **speed** (float) - Optional - The speech speed, where values less than 1.0 slow down speech and values greater than 1.0 speed it up. ### Request Example ```json { "text": "Good morning! Let's get started.", "voice": "af_heart", "speed": 1.0 } ``` ### Response #### Success Response (200) - **audio** (bytes) - The generated WAV audio file content. #### Response Example (Binary audio data representing the spoken text) ``` -------------------------------- ### Migrate Amazon Polly to Brainiall API (Python) Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt Shows how to synthesize speech using Amazon Polly's boto3 client and contrasts it with using Brainiall's REST API. Emphasizes that Brainiall's approach eliminates the need for AWS credentials and SDK setup, relying on a single API key for authentication. ```python import boto3 polly = boto3.client("polly", region_name="us-east-1") response = polly.synthesize_speech( Text="Hello world", OutputFormat="pcm", VoiceId="Joanna", Engine="neural", SampleRate="24000", ) audio = response["AudioStream"].read() ``` ```python import requests response = requests.post( "https://apim-ai-apis.azure-api.net/v1/tts/synthesize", headers={"Ocp-Apim-Subscription-Key": "YOUR_KEY"}, json={"text": "Hello world", "voice": "af_heart", "speed": 1.0}, ) audio = response.content ``` -------------------------------- ### Migrate Google Cloud TTS to Brainiall API (Python) Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt Demonstrates converting text to speech using Google Cloud's Text-to-Speech client library and then using Brainiall's REST API. Highlights the simplicity of Brainiall's API, requiring only an API key and a JSON payload, unlike the setup needed for Google Cloud. ```python from google.cloud import texttospeech client = texttospeech.TextToSpeechClient() input_text = texttospeech.SynthesisInput(text="Hello world") voice = texttospeech.VoiceSelectionParams( language_code="en-US", ssml_gender=texttospeech.SsmlVoiceGender.FEMALE, ) audio_config = texttospeech.AudioConfig( audio_encoding=texttospeech.AudioEncoding.LINEAR16, speaking_rate=1.0, ) response = client.synthesize_speech( input=input_text, voice=voice, audio_config=audio_config ) audio = response.audio_content ``` ```python import requests response = requests.post( "https://apim-ai-apis.azure-api.net/v1/tts/synthesize", headers={"Ocp-Apim-Subscription-Key": "YOUR_KEY"}, json={"text": "Hello world", "voice": "af_heart", "speed": 1.0}, ) audio = response.content ``` -------------------------------- ### Python: List Available TTS Voices Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt This script demonstrates how to fetch a list of all available Text-to-Speech voices from the API. It uses the 'requests' library to make a GET request to the voices endpoint and then iterates through the response to print voice details like ID, name, gender, and accent. Ensure you replace 'YOUR_KEY' with your actual API key. ```python import requests API_KEY = "YOUR_KEY" HEADERS = {"Ocp-Apim-Subscription-Key": API_KEY} response = requests.get( "https://apim-ai-apis.azure-api.net/v1/tts/voices", headers=HEADERS ) voices = response.json() for voice in voices["voices"]: print(f"{voice['id']:15s} {voice['name']:10s} {voice['gender']:8s} {voice['accent']}") ``` -------------------------------- ### GET /v1/tts/voices Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt Retrieves a list of all available TTS voices, including their IDs, names, genders, and accents. ```APIDOC ## GET /v1/tts/voices ### Description List all available TTS voices with metadata. ### Method GET ### Endpoint https://apim-ai-apis.azure-api.net/v1/tts/voices ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **voices** (array) - A list of voice objects, each containing `id`, `name`, `gender`, and `accent`. - **defaultVoice** (string) - The default voice ID. #### Response Example ```json { "voices": [ {"id": "af_heart", "name": "Heart", "gender": "female", "accent": "american"}, {"id": "af_bella", "name": "Bella", "gender": "female", "accent": "american"}, {"id": "af_nicole", "name": "Nicole", "gender": "female", "accent": "american"}, {"id": "af_sarah", "name": "Sarah", "gender": "female", "accent": "american"}, {"id": "af_sky", "name": "Sky", "gender": "female", "accent": "american"}, {"id": "am_adam", "name": "Adam", "gender": "male", "accent": "american"}, {"id": "am_michael", "name": "Michael", "gender": "male", "accent": "american"}, {"id": "bf_emma", "name": "Emma", "gender": "female", "accent": "british"}, {"id": "bf_isabella", "name": "Isabella", "gender": "female", "accent": "british"}, {"id": "bm_george", "name": "George", "gender": "male", "accent": "british"}, {"id": "bm_lewis", "name": "Lewis", "gender": "male", "accent": "british"}, {"id": "bm_daniel", "name": "Daniel", "gender": "male", "accent": "british"} ], "defaultVoice": "af_heart" } ``` Voice ID naming convention: - `af_` = American female - `am_` = American male - `bf_` = British female - `bm_` = British male ``` -------------------------------- ### Python: TTS Synthesis with Voice and Speed Selection Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt This Python code snippet shows how to synthesize text into speech using specific voice and speed parameters. It defines a function 'synthesize' that makes a POST request to the TTS API. The example demonstrates generating audio for different accents (American female, British male) and adjusting speaking speed for narration and language learning. It saves the generated audio to WAV files. ```python import requests API_KEY = "YOUR_KEY" BASE_URL = "https://apim-ai-apis.azure-api.net/v1/tts" HEADERS = {"Ocp-Apim-Subscription-Key": API_KEY} def synthesize(text: str, voice: str = "af_heart", speed: float = 1.0) -> bytes: """Synthesize text to speech and return WAV audio bytes.""" response = requests.post( f"{BASE_URL}/synthesize", headers=HEADERS, json={"text": text, "voice": voice, "speed": speed} ) response.raise_for_status() return response.content # American female voice audio = synthesize("Good morning! Let's get started.", voice="af_heart") with open("american_female.wav", "wb") as f: f.write(audio) # British male voice audio = synthesize("Good morning! Let's get started.", voice="bm_george") with open("british_male.wav", "wb") as f: f.write(audio) # Slow speed for language learning audio = synthesize("The quick brown fox jumps over the lazy dog.", voice="bf_emma", speed=0.7) with open("slow_british.wav", "wb") as f: f.write(audio) # Fast narration audio = synthesize("Breaking news from the financial markets today.", voice="am_adam", speed=1.3) with open("fast_narration.wav", "wb") as f: f.write(audio) ``` -------------------------------- ### GET /v1/tts/health Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt Checks the health status of the TTS API service, indicating if the model is loaded and the number of available voices. ```APIDOC ## GET /v1/tts/health ### Description Health check endpoint. ### Method GET ### Endpoint https://apim-ai-apis.azure-api.net/v1/tts/health ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **status** (string) - Health status of the service (e.g., "healthy"). - **modelLoaded** (boolean) - Indicates if the speech synthesis model is loaded. - **voices** (integer) - The number of available voices. #### Response Example ```json {"status": "healthy", "modelLoaded": true, "voices": 12} ``` ``` -------------------------------- ### Python: LLM + TTS Pipeline for Podcast Intro Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt This snippet demonstrates a two-step process: first, generating text for a podcast intro using an LLM, and second, converting that generated text into speech using a TTS API. It requires the 'openai' and 'requests' libraries. The output is a WAV audio file named 'podcast_intro.wav'. ```python from openai import OpenAI import requests API_KEY = "YOUR_KEY" client = OpenAI( base_url="https://apim-ai-apis.azure-api.net/v1", api_key=API_KEY ) # Step 1: Generate text with LLM response = client.chat.completions.create( model="claude-haiku-4-5", messages=[{"role": "user", "content": "Write a 2-sentence greeting for a podcast intro."}] ) generated_text = response.choices[0].message.content # Step 2: Convert to speech tts_response = requests.post( "https://apim-ai-apis.azure-api.net/v1/tts/synthesize", headers={"Ocp-Apim-Subscription-Key": API_KEY}, json={"text": generated_text, "voice": "am_michael", "speed": 1.0} ) with open("podcast_intro.wav", "wb") as f: f.write(tts_response.content) print(f"Generated intro: {generated_text}") ``` -------------------------------- ### MCP Server Configuration Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt Configuration details for integrating the Speech AI MCP server, including URL and headers required for authentication. ```APIDOC ## MCP Server Configuration ### Description Configuration settings for the Speech AI MCP server, used for pronunciation services. ### Configuration Example (JSON) ```json { "mcpServers": { "brainiall-speech": { "url": "https://apim-ai-apis.azure-api.net/mcp/pronunciation/mcp", "headers": { "Ocp-Apim-Subscription-Key": "YOUR_KEY", "Accept": "application/json, text/event-stream" } } } } ``` ### Notes - Replace `YOUR_KEY` with your actual API subscription key. - The `Accept` header is important for receiving server-sent events if applicable. ``` -------------------------------- ### Generate Language Learning Audio with Python Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt Generates practice audio at slower speeds for language learners. It iterates through predefined lessons and phrases, synthesizing audio for each using the Azure AI TTS API and saving them as WAV files. Requires the 'requests' library. ```python import requests API_KEY = "YOUR_KEY" BASE_URL = "https://apim-ai-apis.azure-api.net/v1/tts" HEADERS = {"Ocp-Apim-Subscription-Key": API_KEY} LESSONS = { "greetings": [ ("Hello, how are you?", "af_heart", 0.7), ("Good morning, nice to meet you.", "bm_george", 0.7), ("My name is Sarah. What is your name?", "af_sarah", 0.7), ], "directions": [ ("Turn left at the next intersection.", "am_adam", 0.8), ("The restaurant is on the right side of the street.", "bf_emma", 0.8), ("Go straight ahead for two blocks.", "bm_lewis", 0.8), ], } for lesson_name, phrases in LESSONS.items(): for i, (text, voice, speed) in enumerate(phrases): response = requests.post( f"{BASE_URL}/synthesize", headers=HEADERS, json={"text": text, "voice": voice, "speed": speed}, ) filename = f"lessons/{lesson_name}_{i+1:02d}.wav" with open(filename, "wb") as f: f.write(response.content) print(f" {filename}: {text}") ``` -------------------------------- ### Python Async TTS Synthesis with httpx Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt This snippet demonstrates asynchronous text-to-speech synthesis using Python's httpx library. It requires an API key and a base URL for the TTS service. The function takes text, voice, and speed as input and returns the synthesized audio as bytes. It handles HTTP POST requests and raises exceptions for non-successful responses. ```python import httpx import asyncio from pathlib import Path API_KEY = "YOUR_KEY" BASE_URL = "https://apim-ai-apis.azure-api.net/v1/tts" async def synthesize_async( text: str, voice: str = "af_heart", speed: float = 1.0, client: httpx.AsyncClient | None = None, ) -> bytes: """Async text-to-speech synthesis.""" _client = client or httpx.AsyncClient(timeout=30.0) try: response = await _client.post( f"{BASE_URL}/synthesize", headers={"Ocp-Apim-Subscription-Key": API_KEY}, json={"text": text, "voice": voice, "speed": speed}, ) response.raise_for_status() return response.content finally: if client is None: await _client.aclose() async def batch_synthesize(items: list[dict], output_dir: str = "audio") -> list[str]: """Synthesize multiple texts concurrently. Returns list of file paths.""" Path(output_dir).mkdir(exist_ok=True) async with httpx.AsyncClient(timeout=30.0) as client: tasks = [ synthesize_async( item["text"], item.get("voice", "af_heart"), item.get("speed", 1.0), client=client, ) for item in items ] results = await asyncio.gather(*tasks, return_exceptions=True) paths = [] for i, result in enumerate(results): if isinstance(result, Exception): print(f"Error on item {i}: {result}") continue path = f"{output_dir}/audio_{i:03d}.wav" Path(path).write_bytes(result) paths.append(path) return paths # Usage async def main(): items = [ {"text": "Welcome to our platform.", "voice": "af_heart"}, {"text": "Let's get started with the tutorial.", "voice": "bf_emma"}, {"text": "Thank you for watching.", "voice": "am_michael", "speed": 0.9}, ] paths = await batch_synthesize(items) print(f"Generated {len(paths)} audio files") asyncio.run(main()) ``` -------------------------------- ### Convert Web Content to Audio for Accessibility with Python Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt Provides a function to convert text content into spoken audio, suitable for visually impaired users. It handles text truncation to avoid exceeding API limits and saves the audio as WAV files. Requires the 'requests' library. ```python import requests API_KEY = "YOUR_KEY" TTS_URL = "https://apim-ai-apis.azure-api.net/v1/tts" HEADERS = {"Ocp-Apim-Subscription-Key": API_KEY} def text_to_audio(content: str, voice: str = "am_michael") -> bytes: """Convert text content to audio for accessibility.""" response = requests.post( f"{TTS_URL}/synthesize", headers=HEADERS, json={"text": content[:5000], "voice": voice, "speed": 0.9}, ) response.raise_for_status() return response.content # Example: convert article sections to audio article = { "title": "New Study Shows Benefits of Daily Exercise", "summary": "Researchers at Stanford University found that just 30 minutes of daily exercise can reduce the risk of heart disease by up to 40 percent.", "details": "The study tracked 10,000 participants over five years, measuring cardiovascular health markers quarterly.", } for section, text in article.items(): audio = text_to_audio(text) with open(f"article_{section}.wav", "wb") as f: f.write(audio) ``` -------------------------------- ### MCP Server Configuration for Brainiall Speech AI Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt Provides a JSON configuration snippet for setting up the Speech AI MCP server, specifically for the 'brainiall-speech' service. This configuration includes the server URL and necessary headers, such as the subscription key and accepted content types. ```json { "mcpServers": { "brainiall-speech": { "url": "https://apim-ai-apis.azure-api.net/mcp/pronunciation/mcp", "headers": { "Ocp-Apim-Subscription-Key": "YOUR_KEY", "Accept": "application/json, text/event-stream" } } } } ``` -------------------------------- ### Python: Batch TTS for Multiple Sentences Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt This script processes a list of sentences, converting each into speech using a TTS API and saving them as individual WAV files. It utilizes the `requests` library for API calls and `pathlib` for file management. The script saves audio files in a specified directory and prints progress and audio duration. ```python import requests from pathlib import Path API_KEY = "YOUR_KEY" BASE_URL = "https://apim-ai-apis.azure-api.net/v1/tts" HEADERS = {"Ocp-Apim-Subscription-Key": API_KEY} sentences = [ "Welcome to our language learning platform.", "Today we will practice pronunciation.", "Listen carefully and repeat after me.", "The weather is beautiful today.", "Let's review what we learned yesterday.", ] output_dir = Path("audio_files") output_dir.mkdir(exist_ok=True) for i, text in enumerate(sentences): response = requests.post( f"{BASE_URL}/synthesize", headers=HEADERS, json={"text": text, "voice": "bf_emma", "speed": 0.9} ) filepath = output_dir / f"sentence_{i+1:02d}.wav" filepath.write_bytes(response.content) duration = response.headers.get("X-Audio-Duration-Ms", "?") print(f"[{i+1}/{len(sentences)}] {filepath.name} ({duration}ms): {text[:50]}") print(f"\nGenerated {len(sentences)} audio files in {output_dir}/") ``` -------------------------------- ### List Available Voices API Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt Demonstrates how to fetch and display a list of all available TTS voices using the API, including filtering by accent and gender. ```APIDOC ## GET /v1/tts/voices ### Description Retrieves a list of all available TTS voices, which can then be iterated through to display details like ID, name, gender, and accent. ### Method GET ### Endpoint https://apim-ai-apis.azure-api.net/v1/tts/voices ### Parameters #### Headers - **Ocp-Apim-Subscription-Key** (string) - Required - Your API subscription key. ### Response #### Success Response (200) - **voices** (array) - A list of voice objects, each containing 'id', 'name', 'gender', and 'accent'. ### Response Example ```json { "voices": [ { "id": "af_heart", "name": "American Female", "gender": "female", "accent": "american" }, { "id": "bm_george", "name": "British Male", "gender": "male", "accent": "british" } ] } ``` ``` -------------------------------- ### Generate IVR Prompts with Python Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt Synthesizes voice prompts for interactive voice response (IVR) systems. It processes a dictionary of common IVR phrases, converts them to audio using a specified voice and speed, and saves them as WAV files. Requires the 'requests' library. ```python import requests API_KEY = "YOUR_KEY" TTS_URL = "https://apim-ai-apis.azure-api.net/v1/tts" HEADERS = {"Ocp-Apim-Subscription-Key": API_KEY} IVR_PROMPTS = { "welcome": "Thank you for calling. For English, press one. Para español, presione dos.", "main_menu": "For sales, press one. For support, press two. For billing, press three. To speak with an operator, press zero.", "hold": "Please hold. Your call is important to us. An agent will be with you shortly.", "voicemail": "We're sorry, no one is available to take your call. Please leave a message after the tone.", "hours": "Our office hours are Monday through Friday, 9 AM to 5 PM Eastern Time.", "goodbye": "Thank you for calling. Have a great day. Goodbye.", } for name, text in IVR_PROMPTS.items(): response = requests.post( f"{TTS_URL}/synthesize", headers=HEADERS, json={"text": text, "voice": "af_nicole", "speed": 0.95}, ) with open(f"ivr/{name}.wav", "wb") as f: f.write(response.content) print(f" {name}.wav ({response.headers.get('X-Audio-Duration-Ms')}ms)") ``` -------------------------------- ### JavaScript: List Voices and Synthesize Audio Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt This JavaScript code snippet retrieves a list of available TTS voices and then synthesizes audio for each British voice. It demonstrates iterating through API responses and saving multiple audio files. An API key is required, and it uses fetch for API calls and Node.js's fs module for file operations. ```javascript const API_KEY = "YOUR_KEY"; const BASE_URL = "https://apim-ai-apis.azure-api.net/v1/tts"; const headers = { "Ocp-Apim-Subscription-Key": API_KEY }; // Get available voices const voicesResponse = await fetch(`${BASE_URL}/voices`, { headers }); const { voices } = await voicesResponse.json(); console.log("Available voices:"); voices.forEach((v) => { console.log(` ${v.id} - ${v.name} (${v.gender}, ${v.accent})`); }); // Synthesize with each British voice for (const voice of voices.filter((v) => v.accent === "british")) { const response = await fetch(`${BASE_URL}/synthesize`, { method: "POST", headers: { ...headers, "Content-Type": "application/json" }, body: JSON.stringify({ text: "Good afternoon. How may I assist you?", voice: voice.id, }), }); const audio = Buffer.from(await response.arrayBuffer()); const fs = await import("fs"); fs.writeFileSync(`${voice.id}.wav`, audio); console.log(`Saved ${voice.id}.wav (${voice.name})`); } ``` -------------------------------- ### Python TTS Client with Error Handling and Retries Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt A Python class for TTS synthesis with built-in error handling and automatic retry mechanisms for network requests. It supports synthesizing text, retrieving available voices with filtering, and saving audio directly to a file. Dependencies include the 'requests' and 'pathlib' libraries. ```python import requests import time from pathlib import Path class BrainiallTTS: """Production TTS client with retry logic and error handling.""" def __init__(self, api_key: str, max_retries: int = 3, timeout: float = 30.0): self.base_url = "https://apim-ai-apis.azure-api.net/v1/tts" self.headers = {"Ocp-Apim-Subscription-Key": api_key} self.max_retries = max_retries self.timeout = timeout self._voices_cache = None def synthesize( self, text: str, voice: str = "af_heart", speed: float = 1.0, ) -> dict: """Synthesize text and return audio bytes with metadata.""" if not text or len(text) > 5000: raise ValueError(f"Text must be 1-5000 chars, got {len(text or '')}") if not 0.25 <= speed <= 4.0: raise ValueError(f"Speed must be 0.25-4.0, got {speed}") for attempt in range(self.max_retries): try: response = requests.post( f"{self.base_url}/synthesize", headers=self.headers, json={"text": text, "voice": voice, "speed": speed}, timeout=self.timeout, ) response.raise_for_status() return { "audio": response.content, "duration_ms": int(response.headers.get("X-Audio-Duration-Ms", 0)), "voice": response.headers.get("X-Voice", voice), "text_length": int(response.headers.get("X-Text-Length", len(text))), } except requests.exceptions.RequestException as e: if attempt < self.max_retries - 1: wait = 2 ** attempt print(f"Retry {attempt + 1}/{self.max_retries} after {wait}s: {e}") time.sleep(wait) else: raise def get_voices(self, accent: str | None = None, gender: str | None = None) -> list[dict]: """Get available voices, optionally filtered by accent or gender.""" if self._voices_cache is None: response = requests.get( f"{self.base_url}/voices", headers=self.headers, timeout=self.timeout, ) response.raise_for_status() self._voices_cache = response.json()["voices"] voices = self._voices_cache if accent: voices = [v for v in voices if v["accent"] == accent] if gender: voices = [v for v in voices if v["gender"] == gender] return voices def save(self, text: str, filepath: str, voice: str = "af_heart", speed: float = 1.0): """Synthesize and save to file in one call.""" result = self.synthesize(text, voice, speed) Path(filepath).write_bytes(result["audio"]) return result # Usage tts = BrainiallTTS(api_key="YOUR_KEY") # Get British male voices british_males = tts.get_voices(accent="british", gender="male") print(f"British male voices: {[v['name'] for v in british_males]}") # Synthesize with auto-retry result = tts.save("The quick brown fox jumps over the lazy dog.", "output.wav") print(f"Duration: {result['duration_ms']}ms") ``` -------------------------------- ### Synthesize Text to Speech Audio (Python) Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt This Python code snippet demonstrates how to use the Brainiall TTS API to convert text into speech. It sends a POST request to the /synthesize endpoint with the text, desired voice, and speed, then saves the returned WAV audio data to a file. It also prints response headers for audio duration and voice used. ```python import requests API_KEY = "YOUR_KEY" BASE_URL = "https://apim-ai-apis.azure-api.net/v1/tts" HEADERS = {"Ocp-Apim-Subscription-Key": API_KEY} # Synthesize speech response = requests.post( f"{BASE_URL}/synthesize", headers=HEADERS, json={ "text": "Hello, welcome to our application. How can I help you today?", "voice": "af_heart", "speed": 1.0 } ) # Save the audio file with open("output.wav", "wb") as f: f.write(response.content) print(f"Audio duration: {response.headers.get('X-Audio-Duration-Ms')}ms") print(f"Voice used: {response.headers.get('X-Voice')}") ``` -------------------------------- ### Text-to-Speech (TTS) Client with Error Handling Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt This section details a Python client for the TTS API that includes robust error handling and automatic retry mechanisms for failed requests. ```APIDOC ## POST /v1/tts/synthesize ### Description Synthesizes the provided text into speech audio with customizable voice and speed settings. Includes automatic retry logic for transient network issues. ### Method POST ### Endpoint https://apim-ai-apis.azure-api.net/v1/tts/synthesize ### Parameters #### Headers - **Ocp-Apim-Subscription-Key** (string) - Required - Your API subscription key. #### Request Body - **text** (string) - Required - The text to synthesize. Must be between 1 and 5000 characters. - **voice** (string) - Optional - The identifier for the voice to use. Defaults to "af_heart". - **speed** (float) - Optional - The speech speed multiplier. Must be between 0.25 and 4.0. Defaults to 1.0. ### Request Example ```json { "text": "The quick brown fox jumps over the lazy dog.", "voice": "af_heart", "speed": 1.0 } ``` ### Response #### Success Response (200) - **audio** (bytes) - The synthesized audio content. - **duration_ms** (integer) - The duration of the audio in milliseconds. - **voice** (string) - The voice used for synthesis. - **text_length** (integer) - The length of the input text in characters. #### Response Example (Binary audio data would be returned here, along with metadata headers) ``` ```APIDOC ## GET /v1/tts/voices ### Description Retrieves a list of all available TTS voices. This list can be optionally filtered by accent and gender. ### Method GET ### Endpoint https://apim-ai-apis.azure-api.net/v1/tts/voices ### Parameters #### Headers - **Ocp-Apim-Subscription-Key** (string) - Required - Your API subscription key. #### Query Parameters - **accent** (string) - Optional - Filters voices by accent (e.g., "british", "american"). - **gender** (string) - Optional - Filters voices by gender (e.g., "male", "female"). ### Response #### Success Response (200) - **voices** (array) - A list of available voice objects. - Each voice object contains: - **id** (string) - The unique identifier for the voice. - **name** (string) - The display name of the voice. - **gender** (string) - The gender of the voice (e.g., "male", "female"). - **accent** (string) - The accent of the voice (e.g., "british", "american"). #### Response Example ```json { "voices": [ { "id": "af_heart", "name": "American Female", "gender": "female", "accent": "american" }, { "id": "bm_george", "name": "British Male", "gender": "male", "accent": "british" } ] } ``` ``` -------------------------------- ### JavaScript: Express.js TTS Service Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt This JavaScript code sets up an Express.js server to provide a TTS API endpoint. It handles requests to synthesize speech and retrieve available voices, forwarding them to an external TTS service. It requires an API key, typically set as an environment variable, and uses fetch for API communication. ```javascript import express from "express"; const app = express(); app.use(express.json()); const API_KEY = process.env.BRAINIALL_API_KEY || "YOUR_KEY"; const TTS_URL = "https://apim-ai-apis.azure-api.net/v1/tts"; app.post("/api/speak", async (req, res) => { const { text, voice = "af_heart", speed = 1.0 } = req.body; if (!text || text.length > 5000) { return res.status(400).json({ error: "Text required, max 5000 chars" }); } try { const response = await fetch(`${TTS_URL}/synthesize`, { method: "POST", headers: { "Content-Type": "application/json", "Ocp-Apim-Subscription-Key": API_KEY, }, body: JSON.stringify({ text, voice, speed }), }); if (!response.ok) throw new Error(`TTS failed: ${response.status}`); const audioBuffer = await response.arrayBuffer(); res.set({ "Content-Type": "audio/wav", "X-Audio-Duration-Ms": response.headers.get("X-Audio-Duration-Ms"), "Cache-Control": "public, max-age=3600", }); res.send(Buffer.from(audioBuffer)); } catch (err) { res.status(500).json({ error: err.message }); } }); app.get("/api/voices", async (req, res) => { const response = await fetch(`${TTS_URL}/voices`, { headers: { "Ocp-Apim-Subscription-Key": API_KEY }, }); res.json(await response.json()); }); app.listen(3000, () => console.log("TTS service on :3000")); ``` -------------------------------- ### Python: Notification System with Customizable TTS Voices Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt This Python script implements a notification system that generates spoken notifications as WAV audio files. It uses a dictionary to map notification types to specific TTS voices and speeds, allowing for customized audio output. The script requires the 'requests' library and saves generated audio files in a specified directory. ```python import requests from pathlib import Path from datetime import datetime API_KEY = "YOUR_KEY" TTS_URL = "https://apim-ai-apis.azure-api.net/v1/tts" HEADERS = {"Ocp-Apim-Subscription-Key": API_KEY} # Voice assignment by notification type NOTIFICATION_VOICES = { "alert": {"voice": "am_adam", "speed": 1.1}, # Urgent, authoritative "reminder": {"voice": "af_heart", "speed": 0.95}, # Warm, calm "greeting": {"voice": "bf_emma", "speed": 1.0}, # Friendly, British "news": {"voice": "bm_george", "speed": 1.05}, # Documentary style "tutorial": {"voice": "af_nicole", "speed": 0.85}, # Clear, professional } def generate_notification( message: str, notification_type: str = "reminder", output_dir: str = "notifications", ) -> str: """Generate a spoken notification audio file.""" config = NOTIFICATION_VOICES.get(notification_type, NOTIFICATION_VOICES["reminder"]) Path(output_dir).mkdir(exist_ok=True) response = requests.post( f"{TTS_URL}/synthesize", headers=HEADERS, json={"text": message, **config}, ) response.raise_for_status() timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filepath = f"{output_dir}/{notification_type}_{timestamp}.wav" Path(filepath).write_bytes(response.content) duration = response.headers.get("X-Audio-Duration-Ms", "?") print(f"[{notification_type}] {duration}ms: {message[:60]}...") return filepath # Usage generate_notification("Your meeting starts in 5 minutes.", "alert") generate_notification("Don't forget to review your weekly report.", "reminder") generate_notification("Good morning! Today's weather is sunny with a high of 72.", "greeting") generate_notification("The market closed up 1.2 percent today.", "news") ``` -------------------------------- ### Python: Audiobook Chapter Generator Source: https://raw.githubusercontent.com/fasuizu-br/speech-ai-examples/main/tts-llms-full.txt This script generates an audiobook chapter from a long text by splitting it into manageable chunks. It defines a helper function `split_into_chunks` to divide text at sentence boundaries while respecting a maximum character limit. The main function then iterates through these chunks, synthesizes audio for each, and saves them as part files. ```python import requests import re from pathlib import Path API_KEY = "YOUR_KEY" BASE_URL = "https://apim-ai-apis.azure-api.net/v1/tts" HEADERS = {"Ocp-Apim-Subscription-Key": API_KEY} def split_into_chunks(text: str, max_chars: int = 4500) -> list[str]: """Split text into chunks at sentence boundaries, respecting max_chars.""" sentences = re.split(r'(?<=[.!?])\s+', text) chunks = [] current = "" for sentence in sentences: if len(current) + len(sentence) + 1 > max_chars: if current: chunks.append(current.strip()) current = sentence else: current = f"{current} {sentence}" if current else sentence if current: chunks.append(current.strip()) return chunks def generate_audiobook_chapter( text: str, output_dir: str, voice: str = "af_sarah", speed: float = 0.95, ) -> list[str]: """Generate audiobook audio files from long text. Returns list of file paths.""" Path(output_dir).mkdir(parents=True, exist_ok=True) chunks = split_into_chunks(text) paths = [] total_duration_ms = 0 for i, chunk in enumerate(chunks): response = requests.post( f"{BASE_URL}/synthesize", headers=HEADERS, json={"text": chunk, "voice": voice, "speed": speed}, ) response.raise_for_status() filepath = f"{output_dir}/part_{i+1:03d}.wav" Path(filepath).write_bytes(response.content) duration = int(response.headers.get("X-Audio-Duration-Ms", 0)) total_duration_ms += duration paths.append(filepath) print(f" Part {i+1}/{len(chunks)}: {duration}ms ({len(chunk)} chars)") print(f"\nTotal: {len(chunks)} parts, {total_duration_ms / 1000:.1f}s audio") return paths # Usage chapter_text = """ Once upon a time, in a land far away, there lived a wise old wizard. He spent his days studying ancient texts and brewing magical potions. One morning, a young traveler arrived at his doorstep seeking guidance. The wizard looked at the traveler and smiled knowingly. """ paths = generate_audiobook_chapter(chapter_text, "audiobook/chapter_01", voice="bm_george") ```