我正在向 Google 文本转语音发送 curl 帖子。我有一组 .flac 文件,我想将其发送到 Google Text to Speech 服务,以便将内容写入 txt 文件。
这是我为此编写的代码,它可以工作:
$url = 'https://www.google.com/speech-api/v2/recognize?output=json&lang=it-IT&key=xxx';
$cont2 = array(
'flac/1.flac',
'flac/2.flac',
'flac/3.flac'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: audio/x-flac; rate=44100'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
foreach ($cont2 as $fn) {
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($fn));
$result = curl_exec($ch);
$info = curl_getinfo($ch);
//var_dump($info);
if ($result === false) {
die(curl_error());
}else{
echo "<br />".$fn." upload ok"."<br />";
file_put_contents("pum.txt", $result, FILE_APPEND);
}
}
它就像一个魅力,在“pum.txt”中我写了所有的文件内容,没关系。
我的问题是我不想每次都添加到数组“cont2”中,我需要传递的文件的新名称在“flac 文件夹”中。
为避免这种情况,我使用“scandir”方法,删除“。” 和数组中的“..”字符串并将该数组提供给 CURL_OPT_POSTFIELD,但对 GTT 的调用返回一个空内容。
这是我为此编写的代码(而不是 $cont2 数组)
$directory = 'flac/';
$cont = array_diff(scandir($directory), array('..', '.', '.DS_Store'));
其中的 Print_r 与 $cont2 数组相同:
array(3) {
[3]=>
string(6) "1.flac"
[4]=>
string(6) "2.flac"
[5]=>
string(6) "3.flac"
}
但谷歌 TTS 返回空结果。
有人请告诉我我在哪里犯错了吗?
亲切的问候
布鲁斯
编辑:使用 "$cont = glob("$directory/*.flac");" 解决了这个问题。希望帮助其他一些人。