こんな方におすすめ
- Google text to speechについて知りたい
- Google text to speechを使いたい
- Google text to speech をPythonで動かしたい
今回は、Google text to speechをPython上で実行する方法について記載します。インストールとか苦戦したので、手順についても触れておきます。
Google text to speechとは
簡単にいうと、文字テキストを音声に変換してくれるものです。日本語、英語、様々な言語で使用可能です。文章でも比較的自然な音声スピーチに変換します。
https://cloud.google.com/text-to-speech/ ここのリンクから試してみることができます。
APIを利用する前に必要なこと
Google Cloud Platform の利用登録をする
トップページの「無料トライアル」をクリックし、Googleアカウントでログインします。無料トライアル中もクレジットカードの登録が必要となります。Googleのアカウントで設定されていれば、再登録の必要はないです。また無料トライアル期間が過ぎても、自動更新はされないので、安心して使用できます。
text to speechのAPIを利用する前の環境設定
APIを利用するための環境設定は、以下のサイトに従い、手順通りに実行することをお勧めします。
いろんなサイトを参考にしましたが、結局ここに記載されている通りやるのが一番です。
①https://cloud.google.com の右上のドキュメントをクリックする。
②左のメニュー欄からAIと学習を選択肢、右の欄でテキスト読み上げを選択する。
③Text-to-Speechのドキュメントからクリックスタートを選択する
④クイックスタート:クライアント ライブラリの使用を選択する
⑤Before you begin に従い、1〜6を実行する。全部必ず実行する必要があります。
⑥google-text-to-speechをインストールする。
1 |
pip install --upgrade google-cloud-texttospeech |
プログラムを作成する
まずは、テキストからmp3ファイルを作成します。
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 |
from google.cloud import texttospeech # Instantiates a client client = texttospeech.TextToSpeechClient() # <span class="hutoaka">ここのテキストが音声変換される。ここではHiとしている。</span> synthesis_input = texttospeech.types.SynthesisInput(text="Hi!") # Build the voice request, select the language code ("en-US") and the ssml # voice gender ("neutral") voice = texttospeech.types.VoiceSelectionParams( language_code='en-US', ssml_gender=texttospeech.enums.SsmlVoiceGender.NEUTRAL) # Select the type of audio file you want returned audio_config = texttospeech.types.AudioConfig( audio_encoding=texttospeech.enums.AudioEncoding.MP3) # Perform the text-to-speech requeston the text input with the selected # voice parameters and audio file type response = client.synthesize_speech(synthesis_input, voice, audio_config) # The response's audio_content is binary.<span class="hutoaka">”Hi"という音声のoutput.mp3が作成される。</span> with open('output.mp3', 'wb') as out: # Write the response to the output file. out.write(response.audio_content) print('Audio content written to file "output.mp3"') |
作成したmp3ファイルを再生します。ここでは、pygameのmixerを使用しました。
1 2 3 4 |
from pygame import mixer mixer.init() #初期化 mixer.music.load("output.mp3") #再生ファイル mixer.music.play(1) #再生回数 |
”Hi”という音声が再生されます。
まとめ
google-text-to-speechで文章を音声化することができました。ツイッターを読ませたり、スクレイピングして読ませたりと幅広い応用が可能です。自作の語学学習プログラムも簡単に作れると思います。ぜひトライしてみてください。