If you wish to convert text to speech with AWS Polly within Symfony applications by using AWS SDK for PHP library, you can use example below. For more details read Amazon Polly Documentation page.


Files


.env


# User: These credentials belong to "AmazonPollyFullAccess" user.
AWS_KEY=AMAZON000KEY
AWS_SECRET=AMAZON000SECRET

config/services.yaml


parameters:

# AWS SDK
aws_sdk:
version: 'latest'
region: 'eu-west-2'
credentials:
key: '%env(AWS_KEY)%'
secret: '%env(AWS_SECRET)%'

services:
_defaults:
autowire: true
autoconfigure: true
public: false

...

Aws\Sdk:
arguments:
- '%aws_sdk%'

Util/Aws/AwsUtil.php


declare(strict_types=1);

namespace App\Util\Aws;

use Aws\Sdk;

abstract class AwsUtil
{
protected $sdk;

public function __construct(Sdk $sdk)
{
$this->sdk = $sdk;
}
}

Util/Aws/AwsPollyUtil.php


declare(strict_types=1);

namespace App\Util\Aws;

use App\Exception\AwsUtilException;
use Aws\Polly\Exception\PollyException;

class AwsPollyUtil extends AwsUtil
{
public function getObject(string $narrative): string
{
try {
$result = $this->sdk->createPolly()->synthesizeSpeech([
'OutputFormat' => 'mp3',
'Text' => $narrative,
'TextType' => 'text',
'VoiceId' => 'Amy'
]);

return $result->get('AudioStream')->getContents();
} catch (PollyException $e) {
throw new AwsUtilException($e->getMessage());
}
}
}

Usage


$result = AwsPollyUtil->getObject('Hello World!');

file_put_contents('somewhere/on/the/disk/audio.mp3', $result);