-
Notifications
You must be signed in to change notification settings - Fork 2
/
googletts.php
70 lines (64 loc) · 1.84 KB
/
googletts.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
class GoogleTTS
{
function getSound($text, $apikey, $lang, $voiceName, $folder)
{
//if folder is not exist create folder
if (!file_exists($folder))
{
mkdir($folder, 0777, true);
}
//get md5 hash filename
$file_name = $folder.strtolower(md5($text));
if(file_exists("$file_name.wav"))
{
//if file is exist return filename
return $file_name;
}
else
{
//if file is not exist start process
$text = trim($text);
if($text == '') return false;
//Create request text
$params = [
"audioConfig"=>[
"audioEncoding"=>"ALAW",
"sampleRateHertz"=>8000
],
"input"=>[
"text"=>$text
],
"voice"=>[
"languageCode"=> $lang,
"name" =>$voiceName
]
];
$data_string = json_encode($params);
$url = "https://texttospeech.googleapis.com/v1/text:synthesize?fields=audioContent&key=$apikey";
$handle = curl_init($url);
//Create curl text
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($handle, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string)
]
);
//run curl request
$response = curl_exec($handle);
$responseDecoded = json_decode($response, true);
curl_close($handle);
//if curl request getting back the data
if($responseDecoded['audioContent'])
{
$fp = fopen("${filename}.wav", 'w');
fwrite($fp,base64_decode($responseDecoded['audioContent']));
fclose($fp);
}
return null;
}
}
}
?>