<?php
/**
USAGE
1. You must have composer installed, if not, https://getcomposer.org
2. in a terminal, run `composer install`
3. Change to your aws keys in the top of the file. You can signup on AWS for free.
4. change text and output file and voice in function synthesizeSpeech
*/
putenv("AWS_ACCESS_KEY_ID=xxxxxxxxxxx"); // replace xxxx with your access key (free)
putenv("AWS_SECRET_ACCESS_KEY=xxxxxxxxxxxx"); // replace with your secret key
require_once(__DIR__ . "/vendor/autoload.php"); // autoload all dependencies
use Aws\Exception\AwsException;
use Aws\Polly\PollyClient;
/**
* Calls polly and saves speechfile to outputfile
*/
function synthesizeSpeech($text, $outputfile, $voice = "random") {
$voices = [
"Geraint", "Gwyneth", "Mads", "Naja", "Hans", "Marlene", "Nicole", "Russell", "Amy", "Brian", "Emma", "Raveena", "Ivy", "Joanna", "Joey", "Justin", "Kendra", "Kimberly", "Matthew", "Salli", "Conchita", "Enrique",
"Miguel", "Penelope", "Chantal", "Celine", "Lea", "Mathieu", "Dora", "Karl", "Carla", "Giorgio", "Mizuki", "Liv", "Lotte", "Ruben", "Ewa", "Jacek", "Jan", "Maja", "Ricardo", "Vitoria", "Cristiano",
"Ines", "Carmen", "Maxim", "Tatyana", "Astrid", "Filiz", "Vicki", "Takumi", "Seoyeon", "Aditi", "Zhiyu", "Bianca", "Lucia", "Mia"
];
if($voice == "random")$voice = $voices[ rand(0,count($voices)-1)];
$format = "mp3";
$credentials = new Aws\Credentials\Credentials(getenv('AWS_ACCESS_KEY_ID'), getenv('AWS_SECRET_ACCESS_KEY'));
$client = new Aws\Polly\PollyClient([
'version' => '2016-06-10',
'region' => 'us-east-2',
'credentials' => [
'key' => getenv('AWS_ACCESS_KEY_ID'),
'secret' => getenv('AWS_SECRET_ACCESS_KEY'),
],
]);
try {
$result = $client->synthesizeSpeech([
'Text' => $text,
'TextType' => 'text',
'OutputFormat' => $format,
'VoiceId' => $voice,
]);
$song = $result->get('AudioStream')->getContents();
file_put_contents($outputfile, $song);
} catch (AwsException $e) {
// output error message if fails
echo $e->getMessage();
echo "\n";
}
}
// example one, write one file
synthesizeSpeech("Get fifty-percent discount. Sign up today.", "output.mp3", "random");
// example two, synthesize a whole book
$files=[
'chapter1.txt',
'chapter2.txt',
'chapter3.txt',
];
foreach($files as $file) {
$data = file_get_contents(__DIR__."/".$file);
synthesizeSpeech($data, $file.".mp3", "Astrid");
die();
}