テキストファイルからvoicevoxで音声を作成するスクリプト
Dockerマシンの voicevox で音声を作成するときにコマンドを毎回実行は面倒
ということで
Python スクリプトにして
テキストファイルを引数にして
音声を作成するようにする
元は
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 | import subprocess import pygame import time def generate_and_play_audio_from_text(file_path): # テキストファイルからテキストを読み込む with open (file_path, 'r' ) as file : text = file . read () # JSONファイルを作成するためのcurlコマンド command_json = [ "curl" , "-s" , "-X" , "POST" , "--get" , "--data-urlencode" , f "text={text}" ] # 音声ファイルを作成するためのcurlコマンド command_audio = [ "curl" , "-s" , "-H" , "Content-Type: application/json" , "-X" , "POST" , ] # JSONファイルと音声ファイルを作成 with open ( 'query.json' , 'w' ) as file : subprocess.run(command_json, stdout= file ) with open ( 'audio_output.wav' , 'wb' ) as file : subprocess.run(command_audio, stdout= file ) # Pygameで音声ファイルを再生 pygame.init() pygame.mixer.init() sound = pygame.mixer.Sound( "audio_output.wav" ) sound.play() while pygame.mixer.get_busy(): time . sleep (0.1) # email_body.txtから音声を生成して再生 generate_and_play_audio_from_text( 'email_body.txt' ) |
というgmail本文を抽出したテキストファイルを音声にするコードがあったので
これを改造する
1 | create_voice.py |
として
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 | import subprocess import sys def generate_and_play_audio_from_text(file_path, server_ip): # テキストファイルからテキストを読み込む with open (file_path, 'r' ) as file : text = file . read () # JSONファイルを作成するためのcurlコマンド command_json = [ "curl" , "-s" , "-X" , "POST" , "--get" , "--data-urlencode" , f "text={text}" ] # 音声ファイルを作成するためのcurlコマンド command_audio = [ "curl" , "-s" , "-H" , "Content-Type: application/json" , "-X" , "POST" , ] # JSONファイルと音声ファイルを作成 with open ( 'query.json' , 'w' ) as file : subprocess.run(command_json, stdout= file ) with open ( 'audio_output.wav' , 'wb' ) as file : subprocess.run(command_audio, stdout= file ) # 音声ファイルを再生 subprocess.run([ "afplay" , "audio_output.wav" ]) if __name__ == "__main__" : if len(sys.argv) < 3: print( "Usage: python script.py <file_path> <server_ip>" ) sys. exit (1) file_path = sys.argv[1] server_ip = sys.argv[2] generate_and_play_audio_from_text(file_path, server_ip) |
として
1 | python script.py example.txt 192.168.1.5 |
というように実行すればいけるはず
1 | python create_voice.py voice.txt 192.168.1.69:50021 |
で実行したら
音声が流れて、音声ファイルも作成された