Text to Speech
Turn text into WAV, MP3 or OGG audio in PHP with local VITS, MMS and Bark voice models. CLI and PHP examples, voices, speed and options.
Read text aloud into an audio file with a local transformers text-to-speech model. The output format follows the file extension: WAV, MP3, M4A, FLAC or OGG.
Setup#
vendor/bin/loves-ai setup text-to-speech
vendor/bin/loves-ai pull facebook/mms-tts-eng
Supported models#
Use a model that needs nothing but text:
- VITS and MMS models, e.g.
facebook/mms-tts-eng(one repository per language, such asmms-tts-deuormms-tts-ukr) orkakao-enterprise/vits-ljs. They are small and fast. - Bark, e.g.
suno/bark-small, which has named voices such asv2/en_speaker_6, chosen with--voice.
Models that need extra files or their own Python code are rejected before starting, with an explanation: SpeechT5 (which needs a speaker embedding file), Kokoro and Parler-TTS (which ship their own code), and speech recognition models given to the wrong runner.
From the command line#
vendor/bin/loves-ai text-to-speech facebook/mms-tts-eng "PHP loves AI, and now it can speak." --output=hello.wav
π΅ Turning your words into sound with facebook/mms-tts-engβ¦ How about a hot chocolate while you wait? β
If you wish to see all logs, re-run the command with the "--debug" option.
π Audio saved to /var/www/my-app/hello.wav
Options#
| Option | Meaning |
|---|---|
--output=PATH |
Audio file to write; its extension picks the format: .wav, .mp3, .m4a, .flac, .ogg (default: a timestamped .wav in output_dir) |
--voice=VOICE |
Voice of models that have several, e.g. a Bark preset like v2/en_speaker_6, or a speaker number |
--speed=RATE |
Speaking rate of VITS-style models, e.g. 0.8 slower, 1.2 faster (default: the model's own) |
--seed=N |
Random seed, for reproducible audio |
--device=DEVICE |
cpu, cuda, mps⦠(default: the best available) |
--log-file=PATH |
Append the runner's output to this file |
--debug |
Show the runner's output while speaking |
Defaults come from config/text-to-speech.php (output_dir, log_file).
From PHP#
use PhpLovesAi\Runner\TextToSpeech;
// Finds the runner and the pulled model in the project's .local directory by itself.
$file = (new TextToSpeech())->speak(
model: 'facebook/mms-tts-eng',
text: 'PHP loves AI, and now it can speak.',
outputPath: storage_path('app/hello.mp3'),
speed: 0.9,
);
// '/var/www/my-app/storage/app/hello.mp3'
Errors#
BinaryNotInstalledExceptionwhensetup text-to-speechhas not been runModelNotFoundExceptionwhen the model was not pulled yetUnsupportedModelExceptionwhen the model cannot speakRunFailedException, with the runner's error output, when generation fails, e.g. for an output format it cannot write
Performance#
Small voice models speak a sentence in a second or two on a laptop CPU, but each run loads the model again, so run longer texts in a queue job.