带有PHP的AWS Polly保存.mp3

时间:2018-07-15 04:37:56

标签: amazon-web-services amazon-polly

我需要一个脚本来获取我的文本,使用AWS Polly API将其转换为语音并将其保存为mp3文件在我的服务器上。

当前,当我加载页面时,会出现一个播放器并播放语音剪辑,但是没有下载文件。

我想念什么?

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;

2 个答案:

答案 0 :(得分:1)

您发送的2个响应是一个接一个。第一个将被处理,第二个最有可能被忽略。

基本上,您已经发送完内容后就无法发送标头。重构代码,以便每个请求仅发送1个响应。

答案 1 :(得分:0)

只需将输出保存到新文件中即可

file_put_contents("output.mp3", $resultData);