Skip to content

Instantly share code, notes, and snippets.

@jacobischwartz
Created January 25, 2018 00:20
Show Gist options
  • Save jacobischwartz/492a0492f2030cf9307fd4115eb59d85 to your computer and use it in GitHub Desktop.
Save jacobischwartz/492a0492f2030cf9307fd4115eb59d85 to your computer and use it in GitHub Desktop.
How to use Amazon Polly in PHP to speak some text and save to mp3 file
<?php
try {
// This should be gitignored. Define your API credentials in it. Get the credentials from AWS IAM. Should have full Polly permissions.
require_once 'vendor/aws.config.php';
// The official AWS SDK for PHP, version 3. See https://docs.aws.amazon.com/aws-sdk-php/v3/guide/getting-started/installation.html
require_once "vendor/aws.phar";
$speak_this = 'This is a php test of Polly';
// Check that PHP has permission to create this file in the current directory.
$filename = 'speech.mp3';
$polly = new Aws\Polly\PollyClient([
'region' => 'us-east-1',
'version' => 'latest',
'credentials' => [
'key' => AWS_ACCESS_KEY_ID, // define this in vendor/aws.config.php
'secret' => AWS_SECRET_ACCESS_KEY // define this in vendor/aws.config.php
]
]);
$result = $polly->synthesizeSpeech([
'OutputFormat' => 'mp3',
'Text' => $speak_this,
'TextType' => 'text',
'VoiceId' => 'Russell'
]);
echo 'file: <a href="' . $filename . '">' . $filename . '</a>';
$saved = file_put_contents(__DIR__ . '/' . $filename, $result['AudioStream']->getContents());
echo '<pre>bytes written: ' . var_export($saved, TRUE);
} catch(Exception $e) {
var_export($e);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment