Question

I want to implement simple text-to-speech script in my web application that would dynamically generate mp3's out of given texts.

It needs to run in both:

  • my local WAMP server on windows
  • and my online linux server

eSpeak doesn't offer the highest quality in sound but at least a strong support in languages, simple implementation and also it's free. So after a little digging i realized there are not much examples of integrating it into php. I concluded StackOverflow should contain a simple implementation of a php text to speech script that generates mp3 with eSpeak and lame.

Was it helpful?

Solution

First we need to setup path to espeak and lame. Make sure you have installed both. In my case it looks like this:

I tought, someone might find this useful. I'm using this code to generate my command in local windows wamp server and online linux server:

// APPLICATION PATHS AND CONFIG
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
    //This is a server using Windows!
    define('ESPEAK', '..\application\libraries\espeak-win\command_line\espeak');
    define('LAME', '..\application\libraries\espeak-win\command_line\lame');
} 
else {
    //This is a server not using Windows!
    define('ESPEAK', '/usr/bin/espeak');
    define('LAME', '/usr/bin/lame');
}

Then, write your own command to be executed. I used %s spots to be replaced later with desired values. List of espeak commands can be found here.

In case you don't need mp3 conversion and you are satisfied with .wav files, just remove the part after | (including this character) and replace argument --stdout with this two args -w desired_file_path. In that case make sure to correctly set %s variables later on.

define('COMMAND', ESPEAK.' --stdout -v %s+m3 -p 60 -a 75 -s 130 "%s" | '.LAME.' --preset voice -q 9 --vbr-new - %s');

and then execute the script like this:

$lang_voice = 'en';
$input_text = 'some input text to read';
$file_path = 'voice-cache/output.mp3'
$exe_path = sprintf(COMMAND, $lang_voice, $input_text, $file_path); // fills %s spots
exec($exe_path);

As a last step, just output generated file:

header('Content-Type: audio/mpeg');
header('Content-Length: '.filesize($file_path));
readfile($file_path);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top