Created
September 21, 2025 20:14
-
-
Save libklein/dba40b857594fc3ba136f23a88b4f931 to your computer and use it in GitHub Desktop.
Synthesize audio from text using piper-tts from a onnx model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import argparse | |
| import wave | |
| from pathlib import Path | |
| from piper.voice import PiperVoice | |
| def synthesize_speech( | |
| model_path: Path, model_json_path: Path, text: str, output_path: Path | |
| ): | |
| # Load the voice model | |
| voice = PiperVoice.load(model_path, model_json_path) | |
| fh = None | |
| # Synthesize the text | |
| for chunk in voice.synthesize(str(text)): | |
| if fh is None: | |
| fh = wave.open(str(output_path), "wb") | |
| fh.setframerate(chunk.sample_rate) | |
| fh.setsampwidth(chunk.sample_width) | |
| fh.setnchannels(chunk.sample_channels) | |
| fh.writeframes(chunk.audio_int16_bytes) | |
| if fh is not None: | |
| fh.close() | |
| print(f"Audio saved to {output_path}") | |
| def main(): | |
| # Create argument parser | |
| parser = argparse.ArgumentParser( | |
| description="Synthesize speech from text using piper-tts" | |
| ) | |
| # Add arguments | |
| parser.add_argument( | |
| "--model", | |
| type=Path, | |
| default="./codsworth.onnx", | |
| help="Path to the ONNX voice model file", | |
| ) | |
| parser.add_argument( | |
| "--config", | |
| type=Path, | |
| default="./codsworth.onnx.json", | |
| help="Path to the model's JSON configuration file", | |
| ) | |
| parser.add_argument( | |
| "--text", type=Path, required=True, help="Text to synthesize into speech" | |
| ) | |
| parser.add_argument( | |
| "--output", type=Path, default=Path("output.wav"), help="Output WAV file path" | |
| ) | |
| # Parse arguments | |
| args = parser.parse_args() | |
| model_path = Path(args.model) | |
| config_path = Path(args.config) | |
| # Validate model files exist | |
| if not model_path.exists() and model_path.is_file(): | |
| print(f"Error: Model file '{args.model}' not found") | |
| return | |
| if not config_path.exists() and config_path.is_file(): | |
| print(f"Error: Config file '{args.config}' not found") | |
| return | |
| output_path = Path(args.output) | |
| output_path.parent.mkdir(parents=True, exist_ok=True) | |
| # Synthesize speech | |
| synthesize_speech(model_path, config_path, args.text, output_path) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment