amazon-web-servicesamazon-polly

AWS Polly with PHP save .mp3


I need a script to take my text, convert it to speech using AWS Polly API and save it on my server as mp3 file.

Currently when I load a page a player appears and plays back the speech clip but no file is downloaded.

What am I missing?

require '../../../include/lib/aws/aws-autoloader.php';

// Creating Amazon Polly Client

use Aws\Polly\PollyClient;

$config = [
    'version' => 'latest',
    'region' => 'us-west-2', //region
    'credentials' => [
        'key' => 'MY_KEY',
        'secret' => 'my_AWS_secret',
    ]];

$client = new PollyClient($config);

// Converting Text to Speech via Polly API

$args = [
    'OutputFormat' => 'mp3',
    'Text' => "<speak><prosody rate='medium'>My text goes here..</prosody></speak>",
    'TextType' => 'ssml',
    'VoiceId' => "Joanna",
];

$result = $client->synthesizeSpeech($args);

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

// Listening the text
$size   = strlen($resultData); // File size
$length = $size;           // Content length
$start  = 0;               // Start byte
$end    = $size - 1;       // End byte
header('Content-Transfer-Encoding:chunked');
header("Content-Type: audio/mpeg");
header("Accept-Ranges: 0-$length");
header("Content-Range: bytes $start-$end/$size");
header("Content-Length: $length");
echo $resultData;


// Download the Text to Speech in MP3 Format

header('Content-length: ' . strlen($resultData));
header('Content-Disposition: attachment; filename="./myfile.mp3"');
header('X-Pad: avoid browser bug');
header('Cache-Control: no-cache');
echo $resultData;

Solution

  • Your sending 2 responses one after the other. The first will be processed the second most likely will be ignored.

    Basically you cant send headers after you already sent content. Refactor your code so you only send 1 response per request.