### Install kokoro-onnx and download model files Source: https://context7.com/thewh1teagle/kokoro-onnx/llms.txt Install the library using pip. For GPU support, install with the `[gpu]` extra. Download the required ONNX model and voices binary files. ```bash pip install -U kokoro-onnx # GPU support (Linux/Windows, CUDA) pip install -U "kokoro-onnx[gpu]" # Download required model files wget https://github.com/thewh1teagle/kokoro-onnx/releases/download/model-files-v1.0/kokoro-v1.0.onnx wget https://github.com/thewh1teagle/kokoro-onnx/releases/download/model-files-v1.0/voices-v1.0.bin ``` -------------------------------- ### Install uv package manager Source: https://github.com/thewh1teagle/kokoro-onnx/blob/main/README.md Install the uv package manager, recommended for creating isolated Python environments. This is an optional but suggested step for managing project dependencies. ```console pip install uv ``` -------------------------------- ### Add kokoro-onnx and soundfile dependencies with uv Source: https://github.com/thewh1teagle/kokoro-onnx/blob/main/README.md Add the kokoro-onnx and soundfile libraries to your project's dependencies using uv. This command installs the specified packages into your isolated environment. ```console uv add kokoro-onnx soundfile ``` -------------------------------- ### Enable GPU Acceleration with ONNX Runtime Source: https://context7.com/thewh1teagle/kokoro-onnx/llms.txt Utilize GPU acceleration by installing `kokoro-onnx[gpu]` and ensuring `onnxruntime-gpu` is installed. Kokoro automatically detects and uses available GPU providers like CUDA or TensorRT. You can also force a specific provider using the `ONNX_PROVIDER` environment variable. ```python # Install GPU dependencies # pip install -U "kokoro-onnx[gpu]" import onnxruntime as ort import soundfile as sf from kokoro_onnx import Kokoro # Check available providers providers = ort.get_available_providers() print("Available providers:", providers) # ['TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider'] print(f"CUDA available: {'CUDAExecutionProvider' in providers}") # Kokoro auto-detects onnxruntime-gpu and uses all available providers kokoro = Kokoro("kokoro-v1.0.onnx", "voices-v1.0.bin") samples, sample_rate = kokoro.create( "GPU-accelerated text to speech!", voice="af_sarah", speed=1.0 ) sf.write("gpu_audio.wav", samples, sample_rate) # Force a specific provider via environment variable: # macOS/Linux: ONNX_PROVIDER=CoreMLExecutionProvider python script.py # Windows PS: $env:ONNX_PROVIDER="DmlExecutionProvider"; python script.py ``` -------------------------------- ### Install kokoro-onnx with pip Source: https://github.com/thewh1teagle/kokoro-onnx/blob/main/README.md Install the kokoro-onnx package using pip. This command ensures you get the latest version. ```console pip install -U kokoro-onnx ``` -------------------------------- ### List available voices with Kokoro.get_voices Source: https://context7.com/thewh1teagle/kokoro-onnx/llms.txt Retrieves a sorted list of all available voice names. The second part of the example demonstrates generating and concatenating audio for all voices into a single WAV file. ```python from kokoro_onnx import Kokoro kokoro = Kokoro("kokoro-v1.0.onnx", "voices-v1.0.bin") voices = kokoro.get_voices() print(voices) # Example output: # ['af_heart', 'af_nicole', 'af_sarah', 'am_michael', 'bf_emma', 'bm_george', # 'ef_dora', 'em_alex', 'ff_siwis', 'hf_alpha', 'if_sara', 'jf_alpha', ...] # Iterate and generate a sample for each voice import numpy as np import soundfile as sf from kokoro_onnx.config import SAMPLE_RATE all_audio = [] for voice in kokoro.get_voices(): samples, sr = kokoro.create(f"Hello, I am {voice}.", voice=voice, speed=1.0) all_audio.append(samples) print(f"Generated: {voice}") sf.write("all_voices.wav", np.concatenate(all_audio), SAMPLE_RATE) ``` -------------------------------- ### Custom eSpeak-NG Configuration with EspeakConfig Source: https://context7.com/thewh1teagle/kokoro-onnx/llms.txt Configure custom paths for the eSpeak-NG shared library and data directory using the `EspeakConfig` dataclass. This is useful in environments where eSpeak-NG is not globally installed or the default paths are not accessible. ```python import os from kokoro_onnx import Kokoro, EspeakConfig import soundfile as sf # Option 1: via EspeakConfig dataclass kokoro = Kokoro( "kokoro-v1.0.onnx", "voices-v1.0.bin", espeak_config=EspeakConfig( lib_path="/usr/local/lib/libespeak-ng.so", data_path="/usr/local/share/espeak-ng-data", ), ) # Option 2: via environment variable (equivalent) # export PHONEMIZER_ESPEAK_LIBRARY=/usr/local/lib/libespeak-ng.so kokoro_env = Kokoro( "kokoro-v1.0.onnx", "voices-v1.0.bin", espeak_config=EspeakConfig(lib_path=os.getenv("PHONEMIZER_ESPEAK_LIBRARY")), ) samples, sample_rate = kokoro.create("Custom eSpeak path example.", voice="af_sarah") sf.write("audio.wav", samples, sample_rate) ``` -------------------------------- ### Publish New Version of Kokoro-ONNX Source: https://github.com/thewh1teagle/kokoro-onnx/blob/main/BUILDING.md Use these commands to clean the distribution directory, build the project, and publish it to PyPI. Ensure you have your PyPI token set in the UV_PUBLISH_TOKEN environment variable. ```console rm -rf dist uv build UV_PUBLISH_TOKEN="pypi token here" uv publish ``` -------------------------------- ### Kokoro.__init__ Source: https://context7.com/thewh1teagle/kokoro-onnx/llms.txt Initializes the Kokoro TTS engine by loading the ONNX model and voices binary. It automatically handles CPU/GPU execution providers and allows for custom eSpeak-NG configurations. ```APIDOC ## Kokoro.__init__ — Initialize the TTS engine Constructs a `Kokoro` instance by loading the ONNX model and voices binary. Automatically selects CPU or GPU execution providers. Accepts an optional `EspeakConfig` to customize the eSpeak-NG library/data paths, and an optional `vocab_config` to supply a custom vocabulary dictionary or path. ```python from kokoro_onnx import Kokoro, EspeakConfig # Basic CPU initialization kokoro = Kokoro("kokoro-v1.0.onnx", "voices-v1.0.bin") # With custom eSpeak-NG library path (useful on macOS/custom installs) kokoro = Kokoro( "kokoro-v1.0.onnx", "voices-v1.0.bin", espeak_config=EspeakConfig(lib_path="/usr/local/lib/libespeak-ng.dylib"), ) # With custom eSpeak-NG data directory kokoro = Kokoro( "kokoro-v1.0.onnx", "voices-v1.0.bin", espeak_config=EspeakConfig(data_path="./espeak-ng-data"), ) ``` ``` -------------------------------- ### Initialize Python environment with uv Source: https://github.com/thewh1teagle/kokoro-onnx/blob/main/README.md Initialize a new Python project folder with a specific Python version using uv. This command sets up a virtual environment for your project. ```console uv init -p 3.12 ``` -------------------------------- ### Initialize Kokoro TTS engine Source: https://context7.com/thewh1teagle/kokoro-onnx/llms.txt Construct a Kokoro instance by loading the ONNX model and voices binary. Basic initialization uses default paths. Custom paths for eSpeak-NG library or data can be provided via `EspeakConfig`. ```python from kokoro_onnx import Kokoro, EspeakConfig # Basic CPU initialization kokoro = Kokoro("kokoro-v1.0.onnx", "voices-v1.0.bin") # With custom eSpeak-NG library path (useful on macOS/custom installs) kokoro = Kokoro( "kokoro-v1.0.onnx", "voices-v1.0.bin", espeak_config=EspeakConfig(lib_path="/usr/local/lib/libespeak-ng.dylib"), ) # With custom eSpeak-NG data directory kokoro = Kokoro( "kokoro-v1.0.onnx", "voices-v1.0.bin", espeak_config=EspeakConfig(data_path="./espeak-ng-data"), ) ``` -------------------------------- ### Initialize Kokoro from ONNX Runtime session Source: https://context7.com/thewh1teagle/kokoro-onnx/llms.txt Initialize Kokoro from a pre-configured `onnxruntime.InferenceSession`. This allows fine-grained control over ONNX Runtime settings like thread count or provider options. Ensure the session is created with the correct model and providers. ```python import os import onnxruntime from onnxruntime import InferenceSession from kokoro_onnx import Kokoro # Configure session with CPU core count threads sess_options = onnxruntime.SessionOptions() sess_options.intra_op_num_threads = os.cpu_count() providers = onnxruntime.get_available_providers() print(f"Available providers: {providers}") session = InferenceSession( "kokoro-v1.0.onnx", providers=providers, sess_options=sess_options, ) kokoro = Kokoro.from_session(session, "voices-v1.0.bin") import soundfile as sf samples, sample_rate = kokoro.create("Hello from a custom session!", voice="af_sarah") sf.write("audio.wav", samples, sample_rate) # Output: audio.wav at 24000 Hz ``` -------------------------------- ### Using Kokoro ONNX Constants Source: https://context7.com/thewh1teagle/kokoro-onnx/llms.txt Demonstrates the usage of module-level constants like SAMPLE_RATE and MAX_PHONEME_LENGTH for audio pipeline construction. These constants are useful for setting up output files and understanding processing limits. ```python from kokoro_onnx import SAMPLE_RATE # 24000 Hz from kokoro_onnx.config import MAX_PHONEME_LENGTH # 510 tokens import numpy as np import soundfile as sf print(f"Sample rate: {SAMPLE_RATE} Hz") print(f"Max phoneme length per batch: {MAX_PHONEME_LENGTH}") # Use SAMPLE_RATE when constructing output files manually with sf.SoundFile("output.wav", mode="w", samplerate=SAMPLE_RATE, channels=1) as f: # Write pre-generated audio chunks dummy_chunk = np.zeros(SAMPLE_RATE, dtype=np.float32) # 1 second of silence f.write(dummy_chunk) ``` -------------------------------- ### Format and Lint Code with Ruff Source: https://github.com/thewh1teagle/kokoro-onnx/blob/main/BUILDING.md Run these commands to format your code according to project standards and check for potential issues using Ruff. ```console uv run ruff format uv run ruff check ``` -------------------------------- ### Format Code with Ruff Source: https://github.com/thewh1teagle/kokoro-onnx/blob/main/CONTRIBUTE.md Run this command to format your code according to project standards using ruff. Ensure your code adheres to the project's formatting rules before submitting. ```console uv run ruff format ``` -------------------------------- ### Use Quantized Models (INT8/FP16) Source: https://context7.com/thewh1teagle/kokoro-onnx/llms.txt Employ smaller and faster quantized ONNX models (INT8 or FP16) as direct replacements for the full model. This reduces disk space and speeds up inference with minimal impact on quality. Ensure you download the appropriate quantized model file. ```python import sounddevice as sd from kokoro_onnx import Kokoro # Download a quantized model: # wget https://github.com/thewh1teagle/kokoro-onnx/releases/download/model-files/kokoro-v0_19.int8.onnx # wget https://github.com/thewh1teagle/kokoro-onnx/releases/download/model-files/kokoro-v0_19.fp16.onnx # INT8 quantized (88MB) kokoro = Kokoro("kokoro-v0_19.int8.onnx", "voices-v1.0.bin") samples, sample_rate = kokoro.create( "Hello, this is the quantized model!", voice="af_sarah", speed=1.0 ) sd.play(samples, sample_rate) sd.wait() ``` -------------------------------- ### Asynchronous streaming TTS generation with Kokoro.create_stream Source: https://context7.com/thewh1teagle/kokoro-onnx/llms.txt Generates audio in chunks for low-latency playback. Ideal for real-time applications. Requires `sounddevice` for playback. ```python import asyncio import sounddevice as sd from kokoro_onnx import Kokoro text = """ Breaking news: Scientists have discovered a new exoplanet in the habitable zone of a nearby star system, just 12 light-years from Earth. The planet, designated Kepler-442c, shows promising signs of liquid water on its surface. Mission teams are already planning follow-up observations with the James Webb Space Telescope. """ async def main(): kokoro = Kokoro("kokoro-v1.0.onnx", "voices-v1.0.bin") stream = kokoro.create_stream( text, voice="af_nicole", speed=1.0, lang="en-us", ) chunk_count = 0 async for samples, sample_rate in stream: chunk_count += 1 print(f"Playing chunk {chunk_count}...") sd.play(samples, sample_rate) sd.wait() # Wait for this chunk before playing the next asyncio.run(main()) ``` -------------------------------- ### Kokoro.from_session Source: https://context7.com/thewh1teagle/kokoro-onnx/llms.txt Initializes a Kokoro instance from a pre-configured ONNX Runtime InferenceSession. This is useful for advanced users who need to control ONNX Runtime settings like thread counts or provider options. ```APIDOC ## Kokoro.from_session — Initialize from a pre-configured ONNX session Class method that constructs a `Kokoro` instance from an already-created `onnxruntime.InferenceSession`. Use this when you need fine-grained control over ONNX Runtime settings such as thread count, memory arenas, or provider options. ```python import os import onnxruntime from onnxruntime import InferenceSession from kokoro_onnx import Kokoro # Configure session with CPU core count threads sess_options = onnxruntime.SessionOptions() sess_options.intra_op_num_threads = os.cpu_count() providers = onnxruntime.get_available_providers() print(f"Available providers: {providers}") session = InferenceSession( "kokoro-v1.0.onnx", providers=providers, sess_options=sess_options, ) kokoro = Kokoro.from_session(session, "voices-v1.0.bin") import soundfile as sf samples, sample_rate = kokoro.create("Hello from a custom session!", voice="af_sarah") sf.write("audio.wav", samples, sample_rate) # Output: audio.wav at 24000 Hz ``` ``` -------------------------------- ### Kokoro.create Source: https://context7.com/thewh1teagle/kokoro-onnx/llms.txt Synchronously converts text to a NumPy audio array. Supports various languages, voice styles, and speed controls. Long texts are automatically batched and concatenated. ```APIDOC ## Kokoro.create — Synchronous text-to-speech generation Converts a text string to a NumPy audio array synchronously. Returns a tuple of `(samples: NDArray[float32], sample_rate: int)` where `sample_rate` is always 24000 Hz. Supports speed control (0.5–2.0×), language selection, and direct phoneme input. Long texts are automatically batched and concatenated. ```python import soundfile as sf from kokoro_onnx import Kokoro kokoro = Kokoro("kokoro-v1.0.onnx", "voices-v1.0.bin") # English US, default speed samples, sample_rate = kokoro.create( "Hello! This audio was generated by kokoro-onnx.", voice="af_sarah", speed=1.0, lang="en-us", ) sf.write("hello.wav", samples, sample_rate) # Slower British English samples, sample_rate = kokoro.create( "Good afternoon, this is a slower British English example.", voice="bf_emma", speed=0.85, lang="en-gb", ) sf.write("british.wav", samples, sample_rate) # French samples, sample_rate = kokoro.create( "Bonjour le monde! Comment ça va?", voice="ff_siwis", speed=1.0, lang="fr-fr", ) sf.write("french.wav", samples, sample_rate) print(f"Sample rate: {sample_rate}") # 24000 print(f"Audio length: {len(samples) / sample_rate:.2f}s") ``` ``` -------------------------------- ### Text to phoneme conversion with Tokenizer.phonemize Source: https://context7.com/thewh1teagle/kokoro-onnx/llms.txt Converts text into an IPA phoneme string using eSpeak-NG. The output can be used with `Kokoro.create(..., is_phonemes=True)` to bypass re-phonemization. Requires `sounddevice` for playback. ```python import sounddevice as sd from kokoro_onnx import Kokoro from kokoro_onnx.tokenizer import Tokenizer # Initialize tokenizer independently (inherits default eSpeak config) tokenizer = Tokenizer() text = "Hello world! How are you today?" phonemes = tokenizer.phonemize(text, lang="en-us") print(f"Phonemes: {phonemes}") # Example output: "həlˈoʊ wˈɜːld! hˌaʊ ɑːɹ juː tədˈeɪ?" ``` -------------------------------- ### Generate Multi-Voice Podcast Audio Source: https://context7.com/thewh1teagle/kokoro-onnx/llms.txt Creates multi-speaker audio by generating segments for different voices and concatenating them with random silence pauses. Requires Kokoro ONNX models and soundfile library. ```python import random import numpy as np import soundfile as sf from kokoro_onnx import Kokoro from kokoro_onnx.config import SAMPLE_RATE kokoro = Kokoro("kokoro-v1.0.onnx", "voices-v1.0.bin") script = [ {"voice": "af_sarah", "text": "Welcome to the show! Today we have a very special topic."}, {"voice": "am_michael", "text": "That's right, Sarah. We're talking about the future of AI."}, {"voice": "af_nicole", "text": "I'm excited to be here... this is a fascinating subject..."}, {"voice": "af_sarah", "text": "Let's dive right in. Michael, what's your take?"}, {"voice": "am_michael", "text": "I think we're at an inflection point unlike anything before."}, ] def silence(min_s=0.3, max_s=1.0): duration = random.uniform(min_s, max_s) return np.zeros(int(duration * SAMPLE_RATE), dtype=np.float32) audio_parts = [] for segment in script: samples, sr = kokoro.create(segment["text"], voice=segment["voice"], speed=1.0) audio_parts.append(samples) audio_parts.append(silence()) final_audio = np.concatenate(audio_parts) sf.write("podcast.wav", final_audio, SAMPLE_RATE) print(f"Created podcast.wav ({len(final_audio)/SAMPLE_RATE:.1f}s)") ``` -------------------------------- ### Enable Debug Logging for Kokoro-ONNX Source: https://context7.com/thewh1teagle/kokoro-onnx/llms.txt Activate debug-level logging to gain insights into phonemization, batch processing, latency, and real-time factor (RTF). This can be done programmatically by setting the logger level or via the `LOG_LEVEL=DEBUG` environment variable. ```python import logging import sounddevice as sd import kokoro_onnx from kokoro_onnx import Kokoro # Enable debug logging programmatically logging.getLogger(kokoro_onnx.__name__).setLevel(logging.DEBUG) # Or set the environment variable: LOG_LEVEL=DEBUG kokoro = Kokoro("kokoro-v1.0.onnx", "voices-v1.0.bin") samples, sample_rate = kokoro.create( "Logging enabled.", voice="af_sarah", speed=1.0 ) # Debug output includes: # kokoro-onnx version 0.5.0 on Linux ... # Providers: ['CPUExecutionProvider'] # Phonemes: ləɡɪŋ ɪnˈeɪbəld. # Creating audio for 1 batches for 22 phonemes # Created audio in length of 1.23s for 22 phonemes in 0.45s (RTF: 0.37) sd.play(samples, sample_rate) sd.wait() ``` -------------------------------- ### Run Python script with uv Source: https://github.com/thewh1teagle/kokoro-onnx/blob/main/README.md Execute a Python script using the uv run command. This ensures the script runs within the isolated environment managed by uv. ```console uv run hello.py ``` -------------------------------- ### Synchronous text-to-speech generation Source: https://context7.com/thewh1teagle/kokoro-onnx/llms.txt Convert text to audio synchronously using the `create` method. Supports speed control, language selection, and direct phoneme input. Long texts are automatically batched. The output sample rate is always 24000 Hz. ```python import soundfile as sf from kokoro_onnx import Kokoro kokoro = Kokoro("kokoro-v1.0.onnx", "voices-v1.0.bin") # English US, default speed samples, sample_rate = kokoro.create( "Hello! This audio was generated by kokoro-onnx.", voice="af_sarah", speed=1.0, lang="en-us", ) sf.write("hello.wav", samples, sample_rate) # Slower British English samples, sample_rate = kokoro.create( "Good afternoon, this is a slower British English example.", voice="bf_emma", speed=0.85, lang="en-gb", ) sf.write("british.wav", samples, sample_rate) # French samples, sample_rate = kokoro.create( "Bonjour le monde! Comment ça va?", voice="ff_siwis", speed=1.0, lang="fr-fr", ) sf.write("french.wav", samples, sample_rate) print(f"Sample rate: {sample_rate}") # 24000 print(f"Audio length: {len(samples) / sample_rate:.2f}s") ``` -------------------------------- ### Kokoro.create_stream - Asynchronous streaming TTS generation Source: https://context7.com/thewh1teagle/kokoro-onnx/llms.txt Generates audio asynchronously and yields chunks as they are processed, enabling low-latency playback for long texts. ```APIDOC ## `Kokoro.create_stream` — Asynchronous streaming TTS generation Async generator that yields `(samples, sample_rate)` tuples as each phoneme batch is processed in a background thread. Enables low-latency playback of long texts by delivering the first audio chunk before the entire text is synthesized. Ideal for real-time applications such as live narration or interactive assistants. ```python import asyncio import sounddevice as sd from kokoro_onnx import Kokoro text = """ Breaking news: Scientists have discovered a new exoplanet in the habitable zone of a nearby star system, just 12 light-years from Earth. The planet, designated Kepler-442c, shows promising signs of liquid water on its surface. Mission teams are already planning follow-up observations with the James Webb Space Telescope. """ async def main(): kokoro = Kokoro("kokoro-v1.0.onnx", "voices-v1.0.bin") stream = kokoro.create_stream( text, voice="af_nicole", speed=1.0, lang="en-us", ) chunk_count = 0 async for samples, sample_rate in stream: chunk_count += 1 print(f"Playing chunk {chunk_count}...") sd.play(samples, sample_rate) sd.wait() # Wait for this chunk before playing the next asyncio.run(main()) ``` ``` -------------------------------- ### Check Code with Ruff Source: https://github.com/thewh1teagle/kokoro-onnx/blob/main/CONTRIBUTE.md Execute this command to check your code for linting issues using ruff. This helps maintain code quality and consistency across the project. ```console uv run ruff check ``` -------------------------------- ### Kokoro.create_stream - Save streaming output to file Source: https://context7.com/thewh1teagle/kokoro-onnx/llms.txt Streams audio chunks directly into a WAV file, suitable for very long texts without buffering the entire audio in memory. ```APIDOC ## `Kokoro.create_stream` — Save streaming output to file Stream audio chunks directly into a WAV file using `soundfile.SoundFile` in write mode. This avoids buffering the entire audio in memory, making it suitable for very long texts. ```python import asyncio import soundfile as sf from kokoro_onnx import Kokoro, SAMPLE_RATE text = """ In a distant future, humanity had spread across the solar system. Colonies on Mars had grown into cities, and the asteroid belt hummed with the activity of mining operations. Earth itself had transformed, its cities vertical forests rising above restored oceans. """ async def main(): kokoro = Kokoro("kokoro-v1.0.onnx", "voices-v1.0.bin") stream = kokoro.create_stream(text, voice="af_nicole", speed=1.0, lang="en-us") with sf.SoundFile("output.wav", mode="w", samplerate=SAMPLE_RATE, channels=1) as f: async for samples, sample_rate in stream: f.write(samples) print(f"Wrote {len(samples)} samples ({len(samples)/sample_rate:.2f}s)") asyncio.run(main()) # Output: output.wav written incrementally ``` ``` -------------------------------- ### Tokenizer.phonemize - Text to phoneme conversion Source: https://context7.com/thewh1teagle/kokoro-onnx/llms.txt Converts raw text to an IPA phoneme string using eSpeak-NG, which can be used to skip re-phonemization in `Kokoro.create()`. ```APIDOC ## `Tokenizer.phonemize` — Text to phoneme conversion Converts raw text to an IPA phoneme string using eSpeak-NG. The result can be passed back to `Kokoro.create()` with `is_phonemes=True` to skip re-phonemization, which is useful for caching phonemes or fine-tuning pronunciation. ```python import sounddevice as sd from kokoro_onnx import Kokoro from kokoro_onnx.tokenizer import Tokenizer # Initialize tokenizer independently (inherits default eSpeak config) tokenizer = Tokenizer() text = "Hello world! How are you today?" phonemes = tokenizer.phonemize(text, lang="en-us") print(f"Phonemes: {phonemes}") # Example output: "həlˈoʊ wˈɜːld! hˌaʊ ɑːɹ juː tədˈeɪ?" ``` ``` -------------------------------- ### Save streaming TTS output to a WAV file with Kokoro.create_stream Source: https://context7.com/thewh1teagle/kokoro-onnx/llms.txt Streams audio chunks directly into a WAV file, suitable for very long texts without buffering the entire audio in memory. Requires `soundfile`. ```python import asyncio import soundfile as sf from kokoro_onnx import Kokoro, SAMPLE_RATE text = """ In a distant future, humanity had spread across the solar system. Colonies on Mars had grown into cities, and the asteroid belt hummed with the activity of mining operations. Earth itself had transformed, its cities vertical forests rising above restored oceans. """ async def main(): kokoro = Kokoro("kokoro-v1.0.onnx", "voices-v1.0.bin") stream = kokoro.create_stream(text, voice="af_nicole", speed=1.0, lang="en-us") with sf.SoundFile("output.wav", mode="w", samplerate=SAMPLE_RATE, channels=1) as f: async for samples, sample_rate in stream: f.write(samples) print(f"Wrote {len(samples)} samples ({len(samples)/sample_rate:.2f}s)") asyncio.run(main()) # Output: output.wav written incrementally ``` -------------------------------- ### Kokoro.get_voices - List available voices Source: https://context7.com/thewh1teagle/kokoro-onnx/llms.txt Returns a sorted list of all available voice names loaded from the voices binary file. ```APIDOC ## `Kokoro.get_voices` — List available voices Returns a sorted list of all available voice names loaded from the voices binary file. ```python from kokoro_onnx import Kokoro kokoro = Kokoro("kokoro-v1.0.onnx", "voices-v1.0.bin") voices = kokoro.get_voices() print(voices) # Example output: # ['af_heart', 'af_nicole', 'af_sarah', 'am_michael', 'bf_emma', 'bm_george', # 'ef_dora', 'em_alex', 'ff_siwis', 'hf_alpha', 'if_sara', 'jf_alpha', ...] # Iterate and generate a sample for each voice import numpy as np import soundfile as sf from kokoro_onnx.config import SAMPLE_RATE all_audio = [] for voice in kokoro.get_voices(): samples, sr = kokoro.create(f"Hello, I am {voice}.", voice=voice, speed=1.0) all_audio.append(samples) print(f"Generated: {voice}") sf.write("all_voices.wav", np.concatenate(all_audio), SAMPLE_RATE) ``` ``` -------------------------------- ### Retrieve raw voice style embedding with Kokoro.get_voice_style Source: https://context7.com/thewh1teagle/kokoro-onnx/llms.txt Fetches the raw NumPy style embedding for a voice, allowing for inspection, modification, or blending of voice characteristics. Requires `numpy` and `soundfile`. ```python import numpy as np import soundfile as sf from kokoro_onnx import Kokoro kokoro = Kokoro("kokoro-v1.0.onnx", "voices-v1.0.bin") # Retrieve raw style vectors sarah = kokoro.get_voice_style("af_sarah") # shape: (max_tokens, style_dim) michael = kokoro.get_voice_style("am_michael") print(f"Voice style shape: {sarah.shape}") # Blend two voices 50/50 blend_50_50 = np.add(sarah * 0.5, michael * 0.5) # Blend 70% sarah, 30% michael blend_70_30 = np.add(sarah * 0.7, michael * 0.3) samples, sample_rate = kokoro.create( "This voice is a blend of Sarah and Michael.", voice=blend_70_30, speed=1.0, lang="en-us", ) sf.write("blended.wav", samples, sample_rate) print("Created blended.wav") ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/thewh1teagle/kokoro-onnx/blob/main/BUILDING.md Set the LOG_LEVEL environment variable to DEBUG before running your Python script to enable detailed logging output. ```console LOG_LEVEL=DEBUG python main.py ``` -------------------------------- ### Pass Pre-computed Phonemes to Kokoro Source: https://context7.com/thewh1teagle/kokoro-onnx/llms.txt Use this when you have already phonemized text and want to bypass Kokoro's internal phonemization step for faster inference. Ensure `is_phonemes` is set to `True`. ```python kokoro = Kokoro("kokoro-v1.0.onnx", "voices-v1.0.bin") samples, sample_rate = kokoro.create( phonemes, voice="af_heart", is_phonemes=True, # tell Kokoro not to re-phonemize speed=1.0, ) sd.play(samples, sample_rate) sd.wait() ``` -------------------------------- ### Fix Linting Issues with Ruff Source: https://github.com/thewh1teagle/kokoro-onnx/blob/main/CONTRIBUTE.md Use this command to automatically fix common linting issues identified by ruff. This is a quick way to address safety fixes before committing. ```console uv run ruff check --fix ``` -------------------------------- ### Kokoro.get_voice_style - Retrieve raw voice style embedding Source: https://context7.com/thewh1teagle/kokoro-onnx/llms.txt Returns the raw NumPy style embedding array for a named voice, useful for inspecting, modifying, or blending voice embeddings. ```APIDOC ## `Kokoro.get_voice_style` — Retrieve raw voice style embedding Returns the raw NumPy style embedding array for a named voice. Use this to inspect, modify, or blend voice embeddings before passing them back to `create()`. ```python import numpy as np import soundfile as sf from kokoro_onnx import Kokoro kokoro = Kokoro("kokoro-v1.0.onnx", "voices-v1.0.bin") # Retrieve raw style vectors sarah = kokoro.get_voice_style("af_sarah") # shape: (max_tokens, style_dim) michael = kokoro.get_voice_style("am_michael") print(f"Voice style shape: {sarah.shape}") # Blend two voices 50/50 blend_50_50 = np.add(sarah * 0.5, michael * 0.5) # Blend 70% sarah, 30% michael blend_70_30 = np.add(sarah * 0.7, michael * 0.3) samples, sample_rate = kokoro.create( "This voice is a blend of Sarah and Michael.", voice=blend_70_30, speed=1.0, lang="en-us", ) sf.write("blended.wav", samples, sample_rate) print("Created blended.wav") ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.