Text to Speech using Amazon Polly API in PHP

Jun 26, 2021

Amazon Polly is a cloud service that allows us to convert any Text to Speech in real-time. Also, there is an option to download into MP3 format.

This cloud service that uses a new machine learning technologies to convert text to speech. They offer customers the most natural and human like a original human voice.

You may read more about this service on AWS documentation.

If you don't want to build a PHP application to convert text to speech, then you can use the amazon Polly console directly. You can access it by login into your AWS account.

Download AWS SDK to convert text to speech.

To create the PHP application for Amazon Polly you need to get your AWS security credentials first. You can obtain it by login into the AWS account and then click on 'My Security Credentials' under the my account tab.

require '/amazon-polly-lib/aws-autoloader.php';

use Aws\Polly\PollyClient;

if(isset($_REQUEST['voice']) && $_REQUEST['voice'] != '')
    $voice = $_REQUEST['voice'];
} else {

if(isset($_REQUEST['text']) && $_REQUEST['text'] != '')
      $text = trim(strip_tags($textData));



$config = [
			'version'     => 'latest',
			'region'      => 'us-east-1',
			'credentials' => [
				'key'    => 'ENTER-YOUR-KEY',
				'secret' => 'ENTER-YOUR-SECRET-KEY',

$client = new PollyClient($config);
$args = [
			'OutputFormat' => 'mp3',
			'Text' =>  "<speak><prosody rate='$rate'>".str_replace("&","&",urldecode ($text))."</prosody></speak>",
			'TextType'     => 'ssml',
			'VoiceId' => $voice,
$result  = $client->synthesizeSpeech($args);          

$resultData = $result->get('AudioStream')->getContents();

$size   = strlen($resultData); // File size
$length = $size;           // Content length
$start  = 0;               // Start byte
$end    = $size - 1;       // End byte

if(!$is_download) {
header("Content-Type: audio/mpeg");
header("Accept-Ranges: 0-$length");
header("Content-Range: bytes $start-$end/$size");
header("Content-Length: $length");
echo $resultData;
} else {
header('Content-length: ' . strlen($resultData));
header('Content-Disposition: attachment; filename="polly-text-to-speech.mp3"');
header('X-Pad: avoid browser bug');
header('Cache-Control: no-cache');
echo $resultData;

Copyright 2018. All rights are reserved