こんな方におすすめ
- Pythonで音声翻訳を作りたい
- googletransを使ってみたい
- ポケトークを自作してみたい
今回はPYTHONで音声翻訳のプログラムを作成します。”おはよう"と音声入力したら、”Good morning."と英語に翻訳された音声が流れます。
ポケトークというとても便利な音声翻訳機がありますが、そんな感じです。GoogleのAPIを使用して実現しているので、Google Cloud Platformの利用登録が必要です。
"テキスト読み上げ"と”音声入力"の2つのjsonが必要ですので、下記サイトを参考に取得しておいてください。
プログラムの内容
以下の手順で音声翻訳を実現しております。
- Pyaudioを使って、翻訳したい内容を音声で録音してwavファイル作成
- Googleのspeechモジュールの関数を使って、 wavファイルの音声をテキストに変換する
- googletransのモジュールの関数を使って、変換した言語に翻訳する
- Googleのtexttospeechモジュールを使って、翻訳変換した文mp3形式で音声ファイルにする。
- mixerモジュールを使ってMP3ファイルを再生する
もっとスマートに実現する方法もあると思いますが、今回は、これまでに作成したプログラムを流用し実現しています。
音声を録音してwaveファイルを作成する関数を作る
引数はファイル名と録音時間です。sample.wavファイルに翻訳の元となる音声を録音するために使用します。
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 |
import pyaudio import numpy import wave WAVE_OUTPUT_FILENAME = "sample.wav" iDeviceIndex = 0 def MakeWavFile(FileName = "sample.wav", Record_Seconds = 5): chunk = 1024 FORMAT = pyaudio.paInt16 #monoral CHANNELS = 1 #sampling rate for wav RATE = 44100 p = pyaudio.PyAudio() stream = p.open(format = FORMAT, channels = CHANNELS, rate = RATE, input = True, frames_per_buffer = chunk) #Start Record print("Recording...") all = [] for i in range(0, int(RATE / chunk * Record_Seconds)): data = stream.read(chunk) all.append(data) #Finished Record print("Finished") stream.close() p.terminate() wavFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb') wavFile.setnchannels(CHANNELS) wavFile.setsampwidth(p.get_sample_size(FORMAT)) wavFile.setframerate(RATE) wavFile.writeframes(b"".join(all)) wavFile.close() |
音声ファイルを文字に変換する関数を作る
録音した音声ファイルを文字に変換する関数を作成します。 googleのspeechモジュールを使用します。message_stackに結果を返します。
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 |
import io import os # Imports the Google Cloud client library from google.cloud import speech from google.cloud.speech import enums from google.cloud.speech import types def speech_to_char(): # Instantiates a client client = speech.SpeechClient() # The name of the audio file to transcribe file_name = os.path.join('sample.wav') with io.open(file_name, 'rb') as audio_file: content = audio_file.read() audio = types.RecognitionAudio(content=content) config = types.RecognitionConfig( encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16, sample_rate_hertz=44100, #Japanese language language_code='ja-JP') response = client.recognize(config, audio) message_stack="" for result in response.results: #print('Transcript: {}'.format(result.alternatives[0].transcript)) message_stack +="{}".format(result.alternatives[0].transcript) return message_stack |
文字を音声に変換して再生する関数を作る
文字を音声に変換して再生する関数を作成します。引数は文字と、ファイル名を変える必要があるときのために用意したcountです。翻訳した文字を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 29 30 31 32 |
from google.cloud import texttospeech from pygame import mixer def voice_from_text(message,count): # Instantiates a client client = texttospeech.TextToSpeechClient() # Set the text input to be synthesized synthesis_input = texttospeech.types.SynthesisInput(text=message) # 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. with open('output'+ str(count)+ '.mp3', 'wb') as out: # Write the response to the output file. out.write(response.audio_content) print('Audio content written to file "output.mp3"') mixer.init() #初期化 mixer.music.load("output" + str(count)+ ".mp3") mixer.music.play(1) |
作成した関数を順に実行します。
作成した関数を順に実行します。翻訳にはTranslatorモジュールを使用しました。
音声入力とテキスト読み上げのjsonが異なるため、文字変換と音声変換の前に、GOOGLE_APPLICATION_CREDENTIALSのjsonの設定を切り替える必要があります。Jupyter notebookを使用する際は、env GOOGLE_APPLICATION_CREDENTIALS= で切り替えが可能です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
from googletrans import Translator import sys translator=Translator() import time #音声録音 MakeWavFile() time.sleep(1) #文字変換 message=speech_to_char() time.sleep(1) #翻訳 translated = translator.translate(message, dest="en"); #音声変換と再生 print(translated.text) voice_from_text(translated.text,1) |
まとめ
"おはよう”と言うと"Good morning"というプログラムを作成することができました。日本語から英語だけではなく、様々な言語で音声翻訳をすることが可能です。ぜひ、試してみてください。