Spaces:
Sleeping
Sleeping
| # piper_engine.py | |
| import io | |
| import numpy as np | |
| import soundfile as sf | |
| from piper.voice import PiperVoice | |
| class PiperEngine: | |
| def __init__(self, model_path): | |
| # Load the voice model | |
| self.voice = PiperVoice.load(model_path) | |
| def synthesize( | |
| self, | |
| text, | |
| speed=1.0, # Default speed multiplier | |
| pitch=1.0, # Default pitch multiplier | |
| sample_rate=22050, | |
| ): | |
| # ----------------------------- | |
| # Important: call synthesize EXACTLY as Piper expects | |
| # ----------------------------- | |
| # Positional arguments only: text, length_scale, pitch_scale | |
| # Do not use keywords like length_scale= or pitch_scale= | |
| audio = self.voice.synthesize(text, speed, pitch) | |
| # ----------------------------- | |
| # Convert to NumPy array and ensure correct shape | |
| # ----------------------------- | |
| audio = np.array(audio, dtype=np.float32) | |
| if audio.ndim == 1: | |
| audio = audio[:, np.newaxis] | |
| # ----------------------------- | |
| # Write to WAV buffer | |
| # ----------------------------- | |
| buffer = io.BytesIO() | |
| sf.write(buffer, audio, sample_rate, format="WAV") | |
| buffer.seek(0) | |
| return buffer | |