### Prepare Assets for iOS Example Source: https://github.com/supertone-inc/supertonic/blob/main/ios/README.md Copies the necessary ONNX models and voice style JSON files from the main assets directory to the `onnx` and `voice_styles` subdirectories within the iOS example app's directory. This is a one-time setup step. ```bash cd ios/ExampleiOSApp mkdir -p onnx voice_styles rsync -a ../../assets/onnx/ onnx/ rsync -a ../../assets/voice_styles/ voice_styles/ ``` -------------------------------- ### Run Supertonic in Browser Source: https://github.com/supertone-inc/supertonic/blob/main/README.md Install dependencies and start the development server for the browser runtime of Supertonic. Navigate to the web directory first. ```bash cd web npm install npm run dev ``` -------------------------------- ### Install Targets Source: https://github.com/supertone-inc/supertonic/blob/main/cpp/CMakeLists.txt Specifies installation rules for the built targets. The 'example_onnx' executable is installed to 'bin', the 'tts_helper' library to 'lib', and 'helper.h' to 'include'. ```cmake # Installation install(TARGETS example_onnx DESTINATION bin) install(TARGETS tts_helper DESTINATION lib) install(FILES helper.h DESTINATION include) ``` -------------------------------- ### Run Supertonic in Node.js Source: https://github.com/supertone-inc/supertonic/blob/main/README.md Install dependencies and start the Node.js runtime for Supertonic. Navigate to the nodejs directory first. ```bash cd nodejs npm install npm start ``` -------------------------------- ### Install Dependencies with npm Source: https://github.com/supertone-inc/supertonic/blob/main/web/README.md Run this command to install the necessary project dependencies. ```bash npm install ``` -------------------------------- ### Install ONNX Runtime on macOS Source: https://github.com/supertone-inc/supertonic/blob/main/go/README.md Installs the ONNX Runtime C library using Homebrew on macOS. This is a prerequisite for running the Go inference examples. ```bash brew install onnxruntime ``` -------------------------------- ### Install Dependencies Source: https://github.com/supertone-inc/supertonic/blob/main/csharp/README.md Run this command to restore project dependencies. Ensure you have the .NET 9.0 SDK or a newer compatible runtime installed. ```bash dotnet restore ``` -------------------------------- ### Start Development Server with npm Source: https://github.com/supertone-inc/supertonic/blob/main/web/README.md Execute this command to launch the local development server and access the demo in your browser. ```bash npm run dev ``` -------------------------------- ### Run Python Example ONNX Source: https://github.com/supertone-inc/supertonic/blob/main/README.md Navigate to the Python directory, synchronize dependencies, and run the example ONNX script to generate speech. ```bash cd py uv sync uv run example_onnx.py ``` -------------------------------- ### Install Rust Source: https://github.com/supertone-inc/supertonic/blob/main/rust/README.md Installs Rust using the official installation script. Ensure you have curl installed. ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` -------------------------------- ### Install Supertonic Python SDK Source: https://github.com/supertone-inc/supertonic/blob/main/README.md Install the Supertonic Python package using pip. This is the first step to using the SDK. ```bash pip install supertonic ``` -------------------------------- ### Run Supertonic in Go Source: https://github.com/supertone-inc/supertonic/blob/main/README.md Download Go modules and run the Go example for Supertonic. Navigate to the go directory first. ```bash cd go go mod download go run example_onnx.go helper.go ``` -------------------------------- ### Run Supertonic in Java Source: https://github.com/supertone-inc/supertonic/blob/main/README.md Build and run the Java example for Supertonic. Navigate to the java directory first. ```bash cd java mvn clean install mvn exec:java ``` -------------------------------- ### Install ONNX Runtime and Dependencies (Ubuntu/Debian) Source: https://github.com/supertone-inc/supertonic/blob/main/cpp/README.md Installs necessary build tools, the nlohmann/json library, and downloads/installs the ONNX Runtime for Linux x64. Ensure ONNX Runtime version compatibility. ```bash sudo apt-get install -y cmake g++ nlohmann-json3-dev wget https://github.com/microsoft/onnxruntime/releases/download/v1.16.3/onnxruntime-linux-x64-1.16.3.tgz tar -xzf onnxruntime-linux-x64-1.16.3.tgz sudo cp -r onnxruntime-linux-x64-1.16.3/include/* /usr/local/include/ sudo cp -r onnxruntime-linux-x64-1.16.3/lib/* /usr/local/lib/ sudo ldconfig ``` -------------------------------- ### Run Supertonic in Swift Source: https://github.com/supertone-inc/supertonic/blob/main/README.md Build the Swift example in release mode and run the executable. Navigate to the swift directory first. ```bash cd swift swift build -c release .build/release/example_onnx ``` -------------------------------- ### Install ONNX Runtime and Dependencies (macOS) Source: https://github.com/supertone-inc/supertonic/blob/main/cpp/README.md Installs CMake, nlohmann-json, and ONNX Runtime using Homebrew. ```bash brew install cmake nlohmann-json onnxruntime ``` -------------------------------- ### Install ONNX Runtime and Dependencies (Windows vcpkg) Source: https://github.com/supertone-inc/supertonic/blob/main/cpp/README.md Installs nlohmann-json and ONNX Runtime for x64 Windows using vcpkg, then integrates vcpkg with the system. ```powershell vcpkg install nlohmann-json:x64-windows onnxruntime:x64-windows vcpkg integrate install ``` -------------------------------- ### Run Supertonic in Rust Source: https://github.com/supertone-inc/supertonic/blob/main/README.md Build the Rust example in release mode and run the executable. Navigate to the rust directory first. ```bash cd rust cargo build --release ./target/release/example_onnx ``` -------------------------------- ### Run Supertonic in iOS Source: https://github.com/supertone-inc/supertonic/blob/main/README.md Generate Xcode project files and open the project for the iOS example. Navigate to the ios/ExampleiOSApp directory first. Further instructions for running on a device are provided. ```bash cd ios/ExampleiOSApp xcodegen generate open ExampleiOSApp.xcodeproj ``` -------------------------------- ### Run Supertonic in C# Source: https://github.com/supertone-inc/supertonic/blob/main/README.md Restore dependencies and run the C# example for Supertonic. Navigate to the csharp directory first. ```bash cd csharp dotnet restore dotnet run ``` -------------------------------- ### Install ONNX Runtime on Linux Source: https://github.com/supertone-inc/supertonic/blob/main/go/README.md Installs the ONNX Runtime C library on Linux by downloading from GitHub releases and copying files to standard system directories. Ensure you have the necessary permissions. ```bash wget https://github.com/microsoft/onnxruntime/releases/download/v1.16.0/onnxruntime-linux-x64-1.16.0.tgz tar -xzf onnxruntime-linux-x64-1.16.0.tgz sudo cp onnxruntime-linux-x64-1.16.0/lib/* /usr/local/lib/ sudo cp -r onnxruntime-linux-x64-1.16.0/include/* /usr/local/include/ sudo ldconfig ``` -------------------------------- ### Install Node.js Dependencies Source: https://github.com/supertone-inc/supertonic/blob/main/nodejs/README.md Install the necessary Node.js packages for the TTS ONNX implementation. ```bash cd nodejs npm install ``` -------------------------------- ### Install Dependencies with Maven Source: https://github.com/supertone-inc/supertonic/blob/main/java/README.md Installs project dependencies using Maven. Ensure Java Development Kit (JDK) 11+ and Maven 3.6+ are installed. ```bash mvn clean install ``` -------------------------------- ### Run Supertonic Flutter Example Source: https://github.com/supertone-inc/supertonic/blob/main/flutter/README.md Commands to clean the Flutter project, fetch dependencies, and run the application on macOS. ```bash flutter clean flutter pub get flutter run -d macos ``` -------------------------------- ### Install Java and Maven on macOS Source: https://github.com/supertone-inc/supertonic/blob/main/java/README.md Installs OpenJDK 17 and Maven using Homebrew on macOS and sets the necessary environment variables for JAVA_HOME and PATH. ```bash brew install openjdk@17 maven export JAVA_HOME="$(brew --prefix openjdk@17)/libexec/openjdk.jdk/Contents/Home" export PATH="$(brew --prefix openjdk@17)/bin:$PATH" ``` -------------------------------- ### Install xcodegen with Homebrew Source: https://github.com/supertone-inc/supertonic/blob/main/ios/README.md Installs the XcodeGen tool, which is required for generating the Xcode project from the project configuration file. ```bash brew install xcodegen ``` -------------------------------- ### Install uv Package Manager Source: https://github.com/supertone-inc/supertonic/blob/main/py/README.md Installs the uv package manager using a curl script. This is a prerequisite for managing project dependencies. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Run ONNX Example with Text Chunking Source: https://github.com/supertone-inc/supertonic/blob/main/rust/README.md Execute the ONNX example binary with a long text. This automatically splits the text into chunks, synthesizes each chunk, adds pauses, and concatenates them. Automatic chunking is disabled in batch mode. ```bash ./target/release/example_onnx \ --voice-style ../assets/voice_styles/M1.json \ --text "This is a very long text that will be automatically split into multiple chunks. The system will process each chunk separately and then concatenate them together with natural pauses between segments. This ensures that even very long texts can be processed efficiently while maintaining natural speech flow and avoiding memory issues." ``` -------------------------------- ### Run Supertonic in C++ Source: https://github.com/supertone-inc/supertonic/blob/main/README.md Build and run the C++ example for Supertonic using CMake. Navigate to the cpp directory first. ```bash cd cpp mkdir build && cd build cmake .. && cmake --build . --config Release ./example_onnx ``` -------------------------------- ### Download ONNX Models and Presets Source: https://github.com/supertone-inc/supertonic/blob/main/README.md Download the necessary ONNX models and preset voices for Supertonic. Ensure Git LFS is installed and initialized. ```bash git lfs install git clone https://huggingface.co/Supertone/supertonic-3 assets ``` -------------------------------- ### Define Example Executable Source: https://github.com/supertone-inc/supertonic/blob/main/cpp/CMakeLists.txt Creates an executable target named 'example_onnx' from example_onnx.cpp. It links the 'tts_helper' library and ONNX Runtime/nlohmann/json dependencies. ```cmake # Example executable add_executable(example_onnx example_onnx.cpp ) if(onnxruntime_FOUND) target_link_libraries(example_onnx tts_helper onnxruntime::onnxruntime nlohmann_json::nlohmann_json ) else() target_link_libraries(example_onnx tts_helper ${ONNXRUNTIME_LIB} nlohmann_json::nlohmann_json ) endif() ``` -------------------------------- ### Install Project Dependencies with uv Source: https://github.com/supertone-inc/supertonic/blob/main/py/README.md Synchronizes project dependencies using the uv package manager. Alternatively, pip with requirements.txt can be used. ```bash uv sync ``` ```bash pip install -r requirements.txt ``` -------------------------------- ### Clone Supertonic Repository Source: https://github.com/supertone-inc/supertonic/blob/main/README.md Clone the Supertonic repository from GitHub to access the full project and examples. ```bash git clone https://github.com/supertone-inc/supertonic.git cd supertonic ``` -------------------------------- ### Run Default Inference Source: https://github.com/supertone-inc/supertonic/blob/main/cpp/README.md Executes the Supertonic C++ example with default settings for text-to-speech synthesis. Uses a default voice style, text, and output directory. ```bash ./example_onnx ``` -------------------------------- ### Build the project with Swift Package Manager Source: https://github.com/supertone-inc/supertonic/blob/main/swift/README.md Build the project in release mode using Swift Package Manager. Ensure Swift 5.9 or later and macOS 13.0 or later are installed. ```bash swift build -c release ``` -------------------------------- ### Java Text-to-Speech Loading and Synthesis Source: https://context7.com/supertone-inc/supertonic/llms.txt Illustrates how to load text-to-speech models and synthesize speech using the Java SDK. It includes environment setup, model loading, and speech synthesis, along with resource management. ```APIDOC ## Java — `Helper.loadTextToSpeech` / `TextToSpeech.call` Java SDK using `ai.onnxruntime` and Jackson for JSON parsing. Requires creating an `OrtEnvironment` which must be closed after use; all ONNX sessions are managed inside `TextToSpeech` and freed by calling `close()`. ```java import ai.onnxruntime.*; import java.util.*; public class ExampleONNX { public static void main(String[] args) throws Exception { OrtEnvironment env = OrtEnvironment.getEnvironment(); String onnxDir = "../assets/onnx"; TextToSpeech tts = Helper.loadTextToSpeech(onnxDir, false, env); // Using CPU for inference Style style = Helper.loadVoiceStyle( List.of("../assets/voice_styles/M1.json"), true, env ); // Loaded 1 voice styles String text = "The startup secured $5.2M in venture capital."; TTSResult result = Helper.timer("Synthesize", () -> tts.call(text, "en", style, 8, 1.05f, 0.3f, env) ); // Synthesize... // -> Synthesize completed in 0.61 sec float dur = result.duration[0]; int wavLen = (int) (tts.sampleRate * dur); float[] wavOut = Arrays.copyOf(result.wav, wavLen); new java.io.File("results").mkdirs(); Helper.writeWavFile("results/output.wav", wavOut, tts.sampleRate); System.out.printf("Saved results/output.wav (%.2fs)%n", dur); // Saved results/output.wav (2.14s) style.close(); tts.close(); env.close(); } } ``` ``` -------------------------------- ### Run Default TTS Inference Source: https://github.com/supertone-inc/supertonic/blob/main/go/README.md Executes the TTS ONNX inference example with default settings for voice style, text, and output directory. Ensure helper.go is in the same directory. ```bash go run example_onnx.go helper.go ``` -------------------------------- ### Build Supertonic TTS Binary Source: https://github.com/supertone-inc/supertonic/blob/main/go/README.md Compile the Supertonic text-to-speech example into a standalone executable binary. This allows for easier deployment and execution without needing to run via `go run`. ```bash go build -o tts_example example_onnx.go helper.go ``` -------------------------------- ### Build Supertonic C++ Project Source: https://github.com/supertone-inc/supertonic/blob/main/cpp/README.md Builds the Supertonic C++ project using CMake. Assumes you are in the 'cpp' directory and have the necessary dependencies installed. ```bash cd cpp mkdir -p build && cd build cmake .. cmake --build . --config Release ./example_onnx ``` -------------------------------- ### Configure ONNX Runtime Library Path (macOS) Source: https://github.com/supertone-inc/supertonic/blob/main/go/README.md Sets the ONNXRUNTIME_LIB_PATH environment variable for macOS, automatically detecting the Homebrew installation path. This is recommended if the library is not in a standard location. ```bash export ONNXRUNTIME_LIB_PATH=$(brew --prefix onnxruntime 2>/dev/null)/lib/libonnxruntime.dylib ``` -------------------------------- ### Java: Load Text-to-Speech and Synthesize Speech Source: https://context7.com/supertone-inc/supertonic/llms.txt Shows how to load ONNX models and synthesize speech using the Java SDK. Requires proper setup of OrtEnvironment and closing resources after use. Jackson is used for JSON parsing. ```java import ai.onnxruntime.*; import java.util.*; public class ExampleONNX { public static void main(String[] args) throws Exception { OrtEnvironment env = OrtEnvironment.getEnvironment(); String onnxDir = "../assets/onnx"; TextToSpeech tts = Helper.loadTextToSpeech(onnxDir, false, env); // Using CPU for inference Style style = Helper.loadVoiceStyle( List.of("../assets/voice_styles/M1.json"), true, env ); // Loaded 1 voice styles String text = "The startup secured $5.2M in venture capital."; TTSResult result = Helper.timer("Synthesize", () -> tts.call(text, "en", style, 8, 1.05f, 0.3f, env) ); // Synthesize... // -> Synthesize completed in 0.61 sec float dur = result.duration[0]; int wavLen = (int) (tts.sampleRate * dur); float[] wavOut = Arrays.copyOf(result.wav, wavLen); new java.io.File("results").mkdirs(); Helper.writeWavFile("results/output.wav", wavOut, tts.sampleRate); System.out.printf("Saved results/output.wav (%.2fs)%n", dur); // Saved results/output.wav (2.14s) style.close(); tts.close(); env.close(); } } ``` -------------------------------- ### Python TTS Synthesis Example Source: https://github.com/supertone-inc/supertonic/blob/main/README.md Basic usage of the Supertonic TTS SDK in Python. Automatically downloads models on first run. Customize voice style, language, quality, and speed for speech synthesis. ```python from supertonic import TTS # First run downloads the model from Hugging Face automatically. tts = TTS(auto_download=True) style = tts.get_voice_style(voice_name="M1") text = "Supertonic is a lightning fast, on-device TTS system." wav, duration = tts.synthesize( text=text, lang="en", # Language code (e.g., "en", "ko", "na" for language-agnostic) voice_style=style, # Voice style object total_steps=8, # Quality: 5 (low) to 12 (high), default 8 (medium) speed=1.05, # Speed: 0.7 (slow) to 2.0 (fast) ) # wav: numpy array of shape (1, num_samples,) with dtype=np.float32, sampled at 44100 Hz # duration: numpy array of shape (1,) containing the duration of the generated audio in seconds tts.save_audio(wav, "output.wav") # import soundfile as sf # sf.write("output.wav", wav.squeeze(), 44100) print(f"Generated {duration[0]:.2f}s of audio") ``` -------------------------------- ### Manual ONNX Runtime Library Path Configuration Source: https://github.com/supertone-inc/supertonic/blob/main/go/README.md Manually sets the ONNXRUNTIME_LIB_PATH environment variable for either Linux or macOS. Use this if automatic detection fails or if the library is installed in a custom location. ```bash export ONNXRUNTIME_LIB_PATH=/path/to/libonnxruntime.so # Linux # or export ONNXRUNTIME_LIB_PATH=/path/to/libonnxruntime.dylib # macOS ``` -------------------------------- ### Build a Fat JAR for TTS Inference Source: https://github.com/supertone-inc/supertonic/blob/main/java/README.md Creates a standalone JAR file containing all dependencies for the TTS inference application. This allows for direct execution without needing Maven installed on the target system. ```bash mvn clean package ``` -------------------------------- ### Go Text-to-Speech with ONNX Runtime Go Source: https://context7.com/supertone-inc/supertonic/llms.txt This Go snippet demonstrates initializing ONNX Runtime, loading models, and performing text-to-speech synthesis. It automatically detects the ONNX Runtime shared library. Ensure the `ONNXRUNTIME_LIB_PATH` environment variable is set if the library is not in a standard location. ```go package main import ( "fmt" "os" ) func main() { // Initialize ONNX Runtime (auto-detects libonnxruntime path) if err := InitializeONNXRuntime(); err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) os.Exit(1) } onnxDir := "../assets/onnx" cfg, err := LoadCfgs(onnxDir) if err != nil { panic(err) } tts, err := LoadTextToSpeech(onnxDir, false, cfg) if err != nil { panic(err) } defer tts.Destroy() style, err := LoadVoiceStyle([]string{"../assets/voice_styles/M1.json"}, true) if err != nil { panic(err) } defer style.Destroy() text := "The startup secured $5.2M in venture capital." wav, dur, err := tts.Call(text, "en", style, 8, 1.05, 0.3) if err != nil { panic(err) } wavLen := int(float32(tts.SampleRate) * dur) out := make([]float64, wavLen) for i := 0; i < wavLen && i < len(wav); i++ { out[i] = float64(wav[i]) } os.MkdirAll("results", 0o755) if err := writeWavFile("results/output.wav", out, tts.SampleRate); err != nil { panic(err) } fmt.Printf("Saved results/output.wav (%.2fs)\n", dur) // Saved results/output.wav (2.14s) } ``` -------------------------------- ### Go — `LoadTextToSpeech` / `TextToSpeech.Call` Source: https://context7.com/supertone-inc/supertonic/llms.txt Go SDK using `github.com/yalue/onnxruntime_go`. Automatically detects the ONNX Runtime shared library from Homebrew or standard system paths; the path can be overridden via `ONNXRUNTIME_LIB_PATH`. ```APIDOC ## Go — `LoadTextToSpeech` / `TextToSpeech.Call` Go SDK using `github.com/yalue/onnxruntime_go`. Automatically detects the ONNX Runtime shared library from Homebrew or standard system paths; the path can be overridden via `ONNXRUNTIME_LIB_PATH`. ```go package main import ( "fmt" "os" ) func main() { // Initialize ONNX Runtime (auto-detects libonnxruntime path) if err := InitializeONNXRuntime(); err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) os.Exit(1) } onnxDir := "../assets/onnx" cfg, err := LoadCfgs(onnxDir) if err != nil { panic(err) } tts, err := LoadTextToSpeech(onnxDir, false, cfg) if err != nil { panic(err) } defer tts.Destroy() style, err := LoadVoiceStyle([]string{"../assets/voice_styles/M1.json"}, true) if err != nil { panic(err) } defer style.Destroy() text := "The startup secured $5.2M in venture capital." wav, dur, err := tts.Call(text, "en", style, 8, 1.05, 0.3) if err != nil { panic(err) } wavLen := int(float32(tts.SampleRate) * dur) out := make([]float64, wavLen) for i := 0; i < wavLen && i < len(wav); i++ { out[i] = float64(wav[i]) } os.MkdirAll("results", 0o755) if err := writeWavFile("results/output.wav", out, tts.SampleRate); err != nil { panic(err) } fmt.Printf("Saved results/output.wav (%.2fs)\n", dur) // Saved results/output.wav (2.14s) } ``` ``` -------------------------------- ### Swift Text-to-Speech Loading and Synthesis Source: https://context7.com/supertone-inc/supertonic/llms.txt Demonstrates how to load text-to-speech models and synthesize speech using the Swift SDK. It covers initializing the environment, loading models, and performing the synthesis. ```APIDOC ## Swift — `loadTextToSpeech` / `TextToSpeech.call` Swift SDK using `OnnxRuntimeBindings`. Loads model files from a directory path, creates `ORTSession` objects within a shared `ORTEnv`, and returns a `TextToSpeech` instance. Throws standard Swift errors on failure. ```swift import Foundation let onnxDir = "../assets/onnx" let env = try ORTEnv(loggingLevel: .warning) let tts = try loadTextToSpeech(onnxDir, false, env) // Using CPU for inference let style = try loadVoiceStyle(["../assets/voice_styles/M1.json"], verbose: true) // Loaded 1 voice styles let text = "The startup secured $5.2M in venture capital." let (wav, dur) = try timer("Synthesize") { try tts.call(text, "en", style, 8, speed: 1.05, silenceDuration: 0.3) } // Synthesize... // -> Synthesize completed in 0.52 sec let wavLen = Int(Float(tts.sampleRate) * dur) let wavTrimmed = Array(wav.prefix(wavLen)) try FileManager.default.createDirectory(atPath: "results", withIntermediateDirectories: true) try writeWavFile("results/output.wav", wavTrimmed, tts.sampleRate) print(String(format: "Saved results/output.wav (%.2fs)", dur)) // Saved results/output.wav (2.14s) ``` ``` -------------------------------- ### Download Go Dependencies Source: https://github.com/supertone-inc/supertonic/blob/main/go/README.md Downloads the necessary Go modules for the project using the Go modules system. ```bash go mod download ``` -------------------------------- ### Build Supertonic Project for Release Source: https://github.com/supertone-inc/supertonic/blob/main/csharp/README.md Use this command to build the project in release mode. This is typically done before deploying or running the compiled executable. ```bash dotnet build -c Release ``` -------------------------------- ### Browser/WebGPU — `loadTextToSpeech` (web) Source: https://context7.com/supertone-inc/supertonic/llms.txt Fetches ONNX models and configuration over HTTP using `onnxruntime-web`. Supports `progressCallback` for loading feedback and `sessionOptions` for enabling WebGPU or WASM execution providers. ```APIDOC ## Browser/WebGPU — `loadTextToSpeech` (web) Fetches all ONNX models and configuration over HTTP using `onnxruntime-web`. Supports a `progressCallback` for loading feedback and a `sessionOptions` object for enabling WebGPU (`executionProviders: ['webgpu']`) or WASM. ```js import { loadTextToSpeech, loadVoiceStyle, writeWavFile } from './helper.js'; // Called during model loading with (modelName, loaded, total) const onModelProgress = (name, loaded, total) => console.log(`Loading ${name}... (${loaded}/${total})`); // Called during denoising steps with (step, totalStep) const onInferProgress = (step, total) => console.log(`Denoising step ${step}/${total}`); const { textToSpeech } = await loadTextToSpeech( '/assets/onnx', { executionProviders: ['webgpu'] }, // or ['wasm'] onModelProgress, ); // Loading Duration Predictor... (1/4) // Loading Text Encoder... (2/4) // ... const style = await loadVoiceStyle(['/assets/voice_styles/M1.json']); const { wav, duration } = await textToSpeech.call( 'Supertonic runs in your browser with zero network dependency.', 'en', style, 8, 1.05, 0.3, onInferProgress, ); // Denoising step 1/8 ... 8/8 const wavBuffer = writeWavFile(wav, textToSpeech.sampleRate); const blob = new Blob([wavBuffer], { type: 'audio/wav' }); const url = URL.createObjectURL(blob); const audio = new Audio(url); audio.play(); ``` ``` -------------------------------- ### Run Batch TTS Inference Source: https://github.com/supertone-inc/supertonic/blob/main/swift/README.md Process multiple voice styles, texts, and languages in a single batch. This example synthesizes English and Korean speech using different voice styles. ```bash .build/release/example_onnx \ --batch \ --voice-style ../assets/voice_styles/M1.json,../assets/voice_styles/F1.json \ --text "The sun sets behind the mountains, painting the sky in shades of pink and orange.|오늘 아침에 공원을 산책했는데, 새소리와 바람 소리가 너무 기분 좋았어요." \ --lang en,ko ``` -------------------------------- ### Swift: Load Text-to-Speech and Synthesize Speech Source: https://context7.com/supertone-inc/supertonic/llms.txt Demonstrates loading ONNX models for text-to-speech and synthesizing speech using the Swift SDK. Ensure ONNX models and voice styles are correctly placed in the specified directories. Errors during loading or synthesis will throw standard Swift errors. ```swift import Foundation let onnxDir = "../assets/onnx" let env = try ORTEnv(loggingLevel: .warning) let tts = try loadTextToSpeech(onnxDir, false, env) // Using CPU for inference let style = try loadVoiceStyle(["../assets/voice_styles/M1.json"], verbose: true) // Loaded 1 voice styles let text = "The startup secured $5.2M in venture capital." let (wav, dur) = try timer("Synthesize") { try tts.call(text, "en", style, 8, speed: 1.05, silenceDuration: 0.3) } // Synthesize... // -> Synthesize completed in 0.52 sec let wavLen = Int(Float(tts.sampleRate) * dur) let wavTrimmed = Array(wav.prefix(wavLen)) try FileManager.default.createDirectory(atPath: "results", withIntermediateDirectories: true) try writeWavFile("results/output.wav", wavTrimmed, tts.sampleRate) print(String(format: "Saved results/output.wav (%.2fs)", dur)) // Saved results/output.wav (2.14s) ``` -------------------------------- ### Find ONNX Runtime Dependency Source: https://github.com/supertone-inc/supertonic/blob/main/cpp/CMakeLists.txt Attempts to find the ONNX Runtime library using multiple methods: CMake config, pkg-config, and manual path searching. It provides installation instructions if the library is not found. ```cmake # Find required packages find_package(PkgConfig REQUIRED) find_package(OpenMP) # ONNX Runtime - Try multiple methods # Method 1: Try to find via CMake config find_package(onnxruntime QUIET CONFIG) if(NOT onnxruntime_FOUND) # Method 2: Try pkg-config pkg_check_modules(ONNXRUNTIME QUIET libonnxruntime) if(ONNXRUNTIME_FOUND) set(ONNXRUNTIME_INCLUDE_DIR ${ONNXRUNTIME_INCLUDE_DIRS}) set(ONNXRUNTIME_LIB ${ONNXRUNTIME_LIBRARIES}) else() # Method 3: Manual search in common locations find_path(ONNXRUNTIME_INCLUDE_DIR NAMES onnxruntime_cxx_api.h PATHS /usr/local/include /opt/homebrew/include /usr/include ${CMAKE_PREFIX_PATH}/include PATH_SUFFIXES onnxruntime ) find_library(ONNXRUNTIME_LIB NAMES onnxruntime libonnxruntime PATHS /usr/local/lib /opt/homebrew/lib /usr/lib ${CMAKE_PREFIX_PATH}/lib ) endif() if(NOT ONNXRUNTIME_INCLUDE_DIR OR NOT ONNXRUNTIME_LIB) message(FATAL_ERROR "ONNX Runtime not found. Please install it:\n" " macOS: brew install onnxruntime\n" " Ubuntu: See README.md for installation instructions") endif() message(STATUS "Found ONNX Runtime:") message(STATUS " Include: ${ONNXRUNTIME_INCLUDE_DIR}") message(STATUS " Library: ${ONNXRUNTIME_LIB}") endif() ``` -------------------------------- ### Web Text-to-Speech with WebGPU Source: https://context7.com/supertone-inc/supertonic/llms.txt Use this snippet to perform text-to-speech in the browser using ONNX Runtime Web with WebGPU acceleration. It supports progress callbacks for model loading and inference. Ensure models are served over HTTP. ```javascript import { loadTextToSpeech, loadVoiceStyle, writeWavFile } from './helper.js'; // Called during model loading with (modelName, loaded, total) const onModelProgress = (name, loaded, total) => console.log(`Loading ${name}... (${loaded}/${total})`); // Called during denoising steps with (step, totalStep) const onInferProgress = (step, total) => console.log(`Denoising step ${step}/${total}`); const { textToSpeech } = await loadTextToSpeech( '/assets/onnx', { executionProviders: ['webgpu'] }, // or ['wasm'] onModelProgress, ); // Loading Duration Predictor... (1/4) // Loading Text Encoder... (2/4) // ... const style = await loadVoiceStyle(['/assets/voice_styles/M1.json']); const { wav, duration } = await textToSpeech.call( 'Supertonic runs in your browser with zero network dependency.', 'en', style, 8, 1.05, 0.3, onInferProgress, ); // Denoising step 1/8 ... 8/8 const wavBuffer = writeWavFile(wav, textToSpeech.sampleRate); const blob = new Blob([wavBuffer], { type: 'audio/wav' }); const url = URL.createObjectURL(blob); const audio = new Audio(url); audio.play(); ``` -------------------------------- ### Node.js — `loadTextToSpeech` / `loadVoiceStyle` Source: https://context7.com/supertone-inc/supertonic/llms.txt Async loader functions for the Node.js SDK. `loadTextToSpeech` creates ONNX Runtime Node.js inference sessions, and `loadVoiceStyle` reads voice-style JSON files into ONNX `Tensor` objects. ```APIDOC ## Node.js — `loadTextToSpeech` / `loadVoiceStyle` Async loader functions for the Node.js SDK. `loadTextToSpeech` creates four ONNX Runtime Node.js inference sessions; `loadVoiceStyle` reads voice-style JSON files and returns ONNX `Tensor` objects ready for inference. ```js import { loadTextToSpeech, loadVoiceStyle, writeWavFile, timer } from './helper.js'; import path from 'path'; const onnxDir = path.resolve('../assets/onnx'); const voiceStylePaths = [path.resolve('../assets/voice_styles/M1.json')]; // Load models (CPU) const textToSpeech = await loadTextToSpeech(onnxDir, false); // Using CPU for inference // Load voice style const style = loadVoiceStyle(voiceStylePaths, true); // Loaded 1 voice styles // Single-speaker synthesis with automatic text chunking const { wav, duration } = await timer('Synthesize', async () => textToSpeech.call( 'The startup secured $5.2M in venture capital.', 'en', style, 8, // total denoising steps 1.05, // speed 0.3, // silence duration between chunks (seconds) ) ); // Synthesize... // -> Synthesize completed in 0.51 sec const wavLen = Math.floor(textToSpeech.sampleRate * duration[0]); writeWavFile('output.wav', wav.slice(0, wavLen), textToSpeech.sampleRate); console.log(`Saved output.wav (${duration[0].toFixed(2)}s)`); // Saved output.wav (2.14s) ``` ``` -------------------------------- ### Run High Quality Inference Source: https://github.com/supertone-inc/supertonic/blob/main/csharp/README.md Increase denoising steps to 10 for improved output quality. This setting increases inference time. ```bash dotnet run -- \ --total-step 10 \ --voice-style ../assets/voice_styles/M1.json \ --text "Increasing the number of denoising steps improves the output's fidelity and overall quality." ``` -------------------------------- ### Rust — `load_text_to_speech` / `TextToSpeech::call` Source: https://context7.com/supertone-inc/supertonic/llms.txt Rust SDK using the `ort` crate (ONNX Runtime 2.x). Loads four ONNX sessions via `Session::builder()` and exposes `call` for single-speaker synthesis with automatic chunking and `batch` for batched inference. ```APIDOC ## Rust — `load_text_to_speech` / `TextToSpeech::call` Rust SDK using the `ort` crate (ONNX Runtime 2.x). Loads four ONNX sessions via `Session::builder()` and exposes `call` for single-speaker synthesis with automatic chunking and `batch` for batched inference. ```rust use anyhow::Result; use std::fs; mod helper; use helper::{load_text_to_speech, load_voice_style, chunk_text, write_wav_file, timer}; fn main() -> Result<()> { let onnx_dir = "../assets/onnx"; let mut tts = timer("Load models", || load_text_to_speech(onnx_dir, false))?; // Load models... // -> Load models completed in 1.23 sec let style = load_voice_style( &[String::from("../assets/voice_styles/M1.json")], true, )?; // Loaded 1 voice styles let text = "The startup secured $5.2M in venture capital."; let (wav, dur) = timer("Synthesize", || { tts.call(text, "en", &style, 8, 1.05, 0.3) })?; // Synthesize... // -> Synthesize completed in 0.47 sec let wav_len = (tts.sample_rate as f32 * dur) as usize; let wav_trimmed = &wav[..wav_len.min(wav.len())]; fs::create_dir_all("results")?; write_wav_file("results/output.wav", wav_trimmed, tts.sample_rate)?; println!("Saved results/output.wav ({:.2}s)", dur); // Saved results/output.wav (2.14s) Ok(()) } ``` ``` -------------------------------- ### Synthesize Speech with Supertonic PyPI API Source: https://context7.com/supertone-inc/supertonic/llms.txt Use the TTS class for automatic model download, voice style management, and audio synthesis. The first run downloads the model. Adjust `total_steps` for quality and `speed` for synthesis rate. ```python from supertonic import TTS # First run automatically downloads the model (~260 MB) from Hugging Face. tts = TTS(auto_download=True) # List available built-in voice styles (M1–M5, F1–F5, etc.) style = tts.get_voice_style(voice_name="F2") # Synthesize — returns (wav: np.ndarray shape [1, N], duration: np.ndarray shape [1,]) wav, duration = tts.synthesize( text="The startup secured $5.2M in venture capital.", lang="en", # 31 language codes + "na" for language-agnostic voice_style=style, total_steps=8, # 5 (fast/low quality) – 12 (slow/high quality) speed=1.05, # 0.7 (slow) – 2.0 (fast) ) # wav shape: (1, num_samples) at 44100 Hz, dtype float32 # duration shape: (1,) containing audio length in seconds tts.save_audio(wav, "output.wav") print(f"Generated {duration[0]:.2f}s of audio") # Generated 2.14s of audio ``` -------------------------------- ### Run Supertonic TTS Binary Source: https://github.com/supertone-inc/supertonic/blob/main/go/README.md Execute the compiled Supertonic text-to-speech binary with specified voice style and text. This is the command used after building the binary. ```bash ./tts_example -voice-style "../assets/voice_styles/M1.json" -text "Hello world" ``` -------------------------------- ### Configure ONNX Runtime Library Path (Linux) Source: https://github.com/supertone-inc/supertonic/blob/main/go/README.md Sets the ONNXRUNTIME_LIB_PATH environment variable for Linux, automatically finding the ONNX Runtime shared object. This is recommended if the library is not in a standard location. ```bash export ONNXRUNTIME_LIB_PATH=$(find /usr/local/lib /usr/lib -name "libonnxruntime.so*" 2>/dev/null | head -n 1) ``` -------------------------------- ### Run Compiled Supertonic Executable Source: https://github.com/supertone-inc/supertonic/blob/main/csharp/README.md Execute the compiled Supertonic application after building it in release mode. The path may vary slightly based on your .NET SDK version. ```bash ./bin/Release/net9.0/Supertonic ``` -------------------------------- ### Run High Quality Inference Source: https://github.com/supertone-inc/supertonic/blob/main/cpp/README.md Increases the number of denoising steps for improved audio fidelity. This results in higher quality output but requires more inference time. ```bash ./example_onnx \ --total-step 10 \ --voice-style ../../assets/voice_styles/M1.json \ --text "Increasing the number of denoising steps improves the output's fidelity and overall quality." ```