Cloud Text-to-Speech API是Google提供的文字转语音服务,目前每月的前1M调用是免费的。
根据官方文档,进行准备工作1-4,5和6不用执行。
进入Cloud Text-to-Speech API页面,点击管理——》凭据——》查看是否已经生成凭据——》将json格式凭据下载至项目根目录
进入项目根目录,增加依赖
| 1 2 | composer require google/cloud-core composer require google/cloud-text-to-speech | 
测试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 | <?php require_once 'vendor/autoload.php'; use Google\Cloud\Core\ServiceBuilder; use Google\Cloud\TextToSpeech\V1\AudioConfig; use Google\Cloud\TextToSpeech\V1\AudioEncoding; use Google\Cloud\TextToSpeech\V1\SynthesisInput; use Google\Cloud\TextToSpeech\V1\TextToSpeechClient; use Google\Cloud\TextToSpeech\V1\VoiceSelectionParams; putenv('GOOGLE_APPLICATION_CREDENTIALS=/var/www/your-project-root-folder/your-project.json'); $cloud = new ServiceBuilder(); $textToSpeechClient = new TextToSpeechClient(); $input = new SynthesisInput(); $input->setSsml('<speak> 青玉案<break time="600ms"/> 作者 王炎2<break time="600ms"/> 深红数点吹花絮<break time="600ms"/> 又燕子、飞来语<break time="600ms"/> 远水平芜春欲暮<break time="600ms"/> 年年长是,清明时候,故遣人憔悴<break time="600ms"/> 竹鸡啼罢山村雨<break time="600ms"/> 正寥落、无情绪<break time="600ms"/> 猛省从前多少事<break time="600ms"/> 绿杨堤上,楼台如画,此景今何处。</speak> '); $voice = new VoiceSelectionParams(); $voice->setLanguageCode('cmn-CN'); $voice->setName('cmn-CN-Wavenet-B'); $audioConfig = new AudioConfig(); $audioConfig->setAudioEncoding(AudioEncoding::MP3); $audioConfig->setSpeakingRate(0.9); $audioConfig->setPitch(0); $resp = $textToSpeechClient->synthesizeSpeech($input, $voice, $audioConfig); $path = tempnam('/var/www/your-project-root-folder', 'gctts_'); // save to file $fp = fopen($path, 'w') or die("Unable to open file!"); fwrite($fp, $resp->getAudioContent()); fclose($fp); if(file_exists($path)) {     header('Content-Type: audio/mpeg');     header('Content-Disposition: inline;filename="gctts_test.mp3"');     header('Content-length: '.filesize($path));     header('Cache-Control: no-cache');     header("Content-Transfer-Encoding: chunked");      readfile($path); } else {     header("HTTP/1.0 404 Not Found"); } unlink($path); | 
以上使用Cloud Text-to-Speech API将一段诗词转换为mp3语音,并推送至浏览器。
know more
https://cloud.google.com/text-to-speech/docs/quickstart-client-libraries?hl=zh_CN
https://github.com/googleapis/google-cloud-php
There are no comments yet