テキストファイルからvoicevoxで音声を作成するスクリプト
Dockerマシンの voicevox で音声を作成するときにコマンドを毎回実行は面倒
ということで
Python スクリプトにして
テキストファイルを引数にして
音声を作成するようにする
元は
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",
"http://{server_ip}/audio_query?speaker=1",
"--get", "--data-urlencode", f"text={text}"
]
# 音声ファイルを作成するためのcurlコマンド
command_audio = [
"curl", "-s", "-H", "Content-Type: application/json", "-X", "POST",
"-d", "@query.json", "http://{server_ip}/synthesis?speaker=1"
]
# 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本文を抽出したテキストファイルを音声にするコードがあったので
これを改造する
create_voice.py
として
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",
f"http://{server_ip}/audio_query?speaker=1",
"--get", "--data-urlencode", f"text={text}"
]
# 音声ファイルを作成するためのcurlコマンド
command_audio = [
"curl", "-s", "-H", "Content-Type: application/json", "-X", "POST",
"-d", "@query.json", f"http://{server_ip}/synthesis?speaker=1"
]
# 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)
として
python script.py example.txt 192.168.1.5
というように実行すればいけるはず
python create_voice.py voice.txt 192.168.1.69:50021
で実行したら
音声が流れて、音声ファイルも作成された