LoginSignup
1
3

More than 5 years have passed since last update.

Goole Cloud Platform の Cloud Text-to-SpeechとPHPで音声データを作成する

Last updated at Posted at 2018-12-08

1.はじめに

Google Cloud PlatformCloud Text-to-SpeechとPHPを使って音声データを作成します。

2.準備

  • GCPのAPI Key
    (GCPのコンソール>APIとサービス>認証情報から生成できます)
  • PHPが動作する環境
    (当方ではphp7.1で動作を確認)

3.開発

create_voice.php
<?php
$google_api_key = '*****'; //ここに自分のAPI key情報をセット
$google_tts_api_url = 'https://texttospeech.googleapis.com/v1/text:synthesize?key='.$google_api_key;
$output_file_name = 'voice.mp3'; //書き出しファイル名

$request_data = [
    'audioConfig' => [
        'audioEncoding' => 'MP3', //出力フォーマット
        'pitch' => 0, //読み上げピッチ調整
        'speakingRate' => 1 //読み上げスピード倍率
    ],
    'input' => [
        'text' => 'this is a pen.', //読み上げたい文字列
    ],
    'voice' => [
        'languageCode' => 'en-US', //言語コード
        'name' => 'en-US-Wavenet-C' //ボイス対象
    ]
];

//apiリクエスト
$ch = curl_init();
$result_json = null;
curl_setopt($ch, CURLOPT_URL, $google_tts_api_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($request_data));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result_json = curl_exec($ch);
curl_close($ch);

//出力
$result_data = json_decode($result_json, true);
file_put_contents($output_file_name, base64_decode($result_data['audioContent']));
exit;

これでphpファイルと同じ階層に音声データが生成されます。

4.まとめ

今回は英語音声を作成しましたが、言語コードを変えれば日本語の読み上げも対応しています。
また、細かな調整やDeepMindによる、より自然な音声データの生成が可能です。

100万文字/月までは無料(2018-12-08時点)なのでちょっとした音声データの生成であればこれで済ますこともできるでしょう。

5.参考リンク

Cloud Text-To-Speech 公式

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3