AIで作る業務動画 Day 5|音声生成スクリプト完成とPhase 1振り返り
今日のゴール
Day 2〜4で作成した機能を統合し、汎用的な音声生成スクリプトを完成させる。あわせてPhase 1を振り返り、学んだことを整理する。
Phase 1最終日。これまで個別に作ってきたスクリプトを一つにまとめる作業だ。
Day 4で掛け合い音声の生成と結合ができるようになった。ただ、2つのスクリプトを順番に実行するのは少し面倒だった。「台本を入れたら一発で結合済み音声が出てくる」状態にしたい。
完成したスクリプト
gemini_tts.pyという名前で統合スクリプトを作成した。
このスクリプトでできること
説明動画のナレーション音声をワンストップで作成できる。
台本(JSON)を用意すれば、1コマンドで:
- 各セリフの音声ファイル(WAV)を生成
- 話者交代のポーズを挿入して結合
- 結合済み音声ファイルを出力
これで「台本を書いたら音声完成」という状態になる。
3つの機能
メインはdialogueだが、修正作業用にtextとcombineも用意した。
| コマンド | 用途 |
|---|---|
dialogue |
台本から全セリフの音声を一括生成(メイン機能) |
text |
1つのセリフだけ音声生成(部分修正用) |
combine |
既存の音声ファイルを結合(再結合用) |
なぜ3つに分けたか
dialogueで一括生成すると、各セリフごとにWAVファイルが残る。
output/
├── 01_kore.wav ← セリフ1
├── 02_charon.wav ← セリフ2
├── 03_kore.wav ← セリフ3
├── ...
├── metadata.json
└── combined.wav ← 結合済み
もし「セリフ3だけ言い回しを変えたい」となったら:
-
textで修正したセリフだけ再生成 →03_kore.wavを上書き -
combineで再結合 → 新しいcombined.wavができる
全部作り直さなくて済むので、APIコストも時間も節約できる。
使い方
メイン:台本から一括生成
python gemini_tts.py dialogue script.json -o output/ --combine
--combineをつけると、個別ファイルと結合済みファイルが一度のコマンドで揃う。
部分修正:1セリフだけ再生成
python gemini_tts.py text "修正後のセリフ" --voice Kore -o output/03_kore.wav
再結合:修正後にまとめ直す
python gemini_tts.py combine output/metadata.json
-oを省略すると、metadata.jsonと同じフォルダにcombined.wavが作られる。
ポーズ設定のカスタマイズ
python gemini_tts.py dialogue script.json -o output/ --combine \
--pause-same 0.3 --pause-different 0.6
Day 4の検証で決めた推奨値(同一話者0.3秒、話者交代0.6秒)がデフォルトになっている。
動作確認
7セリフのサンプル台本で動作確認を実施。
台本を読み込み中: dialogue_sample.json
タイトル: 動画制作パイプラインの紹介
話者数: 2
セリフ数: 7
[1/7] 解説者(Kore)
テキスト: 今日は、AIを使った動画制作の流れについてお話しします。
保存: 01_kore.wav (215,610 bytes, 4.5秒)
[2/7] 質問者(Charon)
テキスト: 動画制作って難しそうですね。プログラミングの知識がなくても大...
保存: 02_charon.wav (257,850 bytes, 5.4秒)
...
==================================================
生成完了
==================================================
成功: 7/7 ファイル
合計時間: 37.5秒
合計サイズ: 1,799,190 bytes
コスト見積: 約3.00円
約30秒で7ファイル+結合済みファイルが生成された。コスト見積もりも表示されるようにした。
Phase 1 コスト実績
5日間で実際に使った音声生成のコストを集計してみた。
| Day | 内容 | 音声秒数 | コスト見積 |
|---|---|---|---|
| Day 2 | セットアップ検証 | 3秒 | 0.24円 |
| Day 3 | ボイス・スタイル検証 | 385秒 | 30.80円 |
| Day 4 | 掛け合い音声検証 | 38秒 | 3.04円 |
| Day 5 | スクリプトテスト | 42.5秒 | 3.40円 |
| 合計 | 468.5秒(約7.8分) | 約37.48円 |
当初の想定「10分で30〜60円」に対して、7.8分で37.48円は想定範囲内。AivisSpeechへのフォールバックは不要と判断した。
正直なところ、Day 3の検証で結構使った。12種類のボイスを試して、スタイル制御も13パターン検証したから仕方ない。本番の動画制作ではもっと効率的に使えるはず。
Phase 1 振り返り
できるようになったこと
-
単一テキストの音声生成
python gemini_tts.py text "テキスト" -o output.wav
-
掛け合い音声の生成
- JSON台本から複数ボイスで一括生成
- 話者交代時のポーズ挿入
-
音声ファイルの結合
- 個別ファイルを自然なポーズで結合
技術的な知見
| 項目 | 結論 |
|---|---|
| 推奨ボイス | Kore(女性・落ち着き)+ Charon(男性・解説) |
| 同一話者ポーズ | 0.3秒 |
| 話者交代ポーズ | 0.6秒 |
| 音声形式 | PCM 16bit / 24kHz / モノラル |
当初計画からの変更
Day 1で方針を変更した。
変更前: AivisSpeech/VOICEVOXで音声生成
変更後: Gemini TTS APIに一本化
理由は3つあった。
- AivisSpeechのインストール・設定が複雑
- Gemini TTS APIは低コスト(想定内で収まった)
- 複数ボイスの切り替えがAPI経由で簡単
結果的に正解だったと思う。セットアップの手間が減って、Day 2からすぐに音声生成に取り組めた。
Phase 2への準備
Phase 2では生成した音声にリップシンク(口パク)をつける。
準備として、以下の成果物をPhase 2に引き継ぐ。
| 成果物 | 説明 |
|---|---|
| gemini_tts.py | 統合音声生成スクリプト |
| 台本JSONフォーマット | 掛け合い音声の標準形式 |
| サンプル音声ファイル | 検証用(Day 3/4で生成済み) |
検証環境
| 項目 | バージョン |
|---|---|
| OS | Windows 11 Pro |
| Python | 3.12.10 |
| google-genai | 1.56.0 |
| 検証日 | 2026-01-02 |
Phase 1が完了した。5日間で音声生成の基盤ができた。
明日からはPhase 2「リップシンク」に入る。Rhubarb Lip Syncを使って、音声に合わせた口の動きを生成する予定だ。
台本フォーマット(dialogue_sample.json)
{
"title": "動画制作パイプラインの紹介",
"description": "AIで業務動画を作る流れを対話形式で説明",
"speakers": {
"A": { "name": "解説者", "voice": "Kore" },
"B": { "name": "質問者", "voice": "Charon" }
},
"dialogue": [
{
"speaker": "A",
"text": "今日は、AIを使った動画制作の流れについてお話しします。"
},
{
"speaker": "B",
"text": "動画制作って難しそうですね。プログラミングの知識がなくても大丈夫ですか?"
},
{
"speaker": "A",
"text": "はい、基本的な手順を覚えれば、非エンジニアの方でも作成できます。"
},
{
"speaker": "B",
"text": "具体的には、どんな手順で進めるのですか?"
},
{
"speaker": "A",
"text": "まず台本を作成し、次にAIで音声を生成します。その後、口パクデータを作成して、最後に動画にまとめます。"
},
{
"speaker": "B",
"text": "なるほど。台本から動画まで、全部自動でできるんですね。"
},
{
"speaker": "A",
"text": "その通りです。一度パイプラインを構築すれば、台本を変えるだけで新しい動画を作れます。"
}
]
}
音声生成スクリプト(gemini_tts.py)
"""
Gemini TTS 音声生成スクリプト
Day 5: Phase 1 完成版
機能:
- 単一テキストの音声生成
- JSON台本からの掛け合い音声生成
- 音声ファイルの結合(ポーズ挿入)
- コスト見積もり表示
使用例:
# 単一テキスト
python gemini_tts.py text "こんにちは" -o hello.wav
# JSON台本から掛け合い音声
python gemini_tts.py dialogue script.json -o output/
# 結合済み音声も生成
python gemini_tts.py dialogue script.json -o output/ --combine
"""
import os
import sys
import json
import wave
import struct
import argparse
import time
from pathlib import Path
from datetime import datetime
# Google Generative AI SDK
try:
from google import genai
from google.genai import types
except ImportError:
print("エラー: google-genai がインストールされていません")
print("pip install google-genai でインストールしてください")
sys.exit(1)
# =============================================================================
# 定数
# =============================================================================
MODEL_NAME = "gemini-2.5-flash-preview-tts"
SAMPLE_RATE = 24000 # Hz
SAMPLE_WIDTH = 2 # 16bit = 2 bytes
CHANNELS = 1 # モノラル
# コスト見積もり(2026年1月時点の概算)
# 参考: 10分の音声 ≈ 30〜60円
COST_PER_SECOND_YEN = 0.08 # 1秒あたり約8銭
# デフォルトボイス
DEFAULT_VOICE = "Kore"
# 利用可能なボイス一覧
AVAILABLE_VOICES = [
"Aoede", "Charon", "Fenrir", "Kore", "Leda",
"Orus", "Puck", "Zephyr" # 日本語推奨
]
# =============================================================================
# 音声処理関数
# =============================================================================
def create_silence(duration_sec: float, sample_rate: int = SAMPLE_RATE) -> bytes:
"""無音データを生成"""
num_samples = int(duration_sec * sample_rate)
return struct.pack('<' + 'h' * num_samples, *([0] * num_samples))
def save_wav(audio_data: bytes, output_path: str,
sample_rate: int = SAMPLE_RATE,
sample_width: int = SAMPLE_WIDTH,
channels: int = CHANNELS):
"""RAW PCMデータをWAVファイルとして保存"""
with wave.open(output_path, "wb") as wav_file:
wav_file.setnchannels(channels)
wav_file.setsampwidth(sample_width)
wav_file.setframerate(sample_rate)
wav_file.writeframes(audio_data)
def read_wav(file_path: str) -> tuple[bytes, dict]:
"""WAVファイルを読み込む"""
with wave.open(file_path, 'rb') as wav:
params = {
'channels': wav.getnchannels(),
'sample_width': wav.getsampwidth(),
'frame_rate': wav.getframerate(),
'n_frames': wav.getnframes()
}
data = wav.readframes(wav.getnframes())
return data, params
def get_audio_duration(audio_data: bytes, sample_rate: int = SAMPLE_RATE) -> float:
"""音声データの長さを秒で計算"""
return len(audio_data) / (sample_rate * SAMPLE_WIDTH)
# =============================================================================
# Gemini TTS API関数
# =============================================================================
def generate_audio(client: genai.Client, text: str, voice: str = DEFAULT_VOICE,
max_retries: int = 3) -> bytes:
"""
Gemini TTS APIで音声を生成
Args:
client: Gemini APIクライアント
text: 読み上げるテキスト
voice: ボイス名
max_retries: 最大リトライ回数
Returns:
RAW PCM音声データ
"""
for attempt in range(max_retries):
try:
response = client.models.generate_content(
model=MODEL_NAME,
contents=f"Read aloud the following text in Japanese: {text}",
config=types.GenerateContentConfig(
response_modalities=["AUDIO"],
speech_config=types.SpeechConfig(
voice_config=types.VoiceConfig(
prebuilt_voice_config=types.PrebuiltVoiceConfig(
voice_name=voice
)
)
)
)
)
part = response.candidates[0].content.parts[0]
return part.inline_data.data
except Exception as e:
if attempt < max_retries - 1:
wait_time = 2 ** attempt # 指数バックオフ
print(f" リトライ ({attempt + 1}/{max_retries}): {wait_time}秒待機...")
time.sleep(wait_time)
else:
raise e
return b''
# =============================================================================
# コマンド: text
# =============================================================================
def cmd_text(args):
"""単一テキストの音声生成"""
api_key = get_api_key()
client = genai.Client(api_key=api_key)
text = args.text
voice = args.voice
output_path = args.output or "output.wav"
print(f"テキスト: {text}")
print(f"ボイス: {voice}")
print(f"出力先: {output_path}")
print()
print("音声生成中...")
audio_data = generate_audio(client, text, voice)
# 保存
save_wav(audio_data, output_path)
# 結果表示
duration = get_audio_duration(audio_data)
file_size = Path(output_path).stat().st_size
estimated_cost = duration * COST_PER_SECOND_YEN
print()
print("=" * 50)
print("生成完了")
print("=" * 50)
print(f"ファイル: {output_path}")
print(f"サイズ: {file_size:,} bytes")
print(f"長さ: {duration:.1f}秒")
print(f"コスト見積: 約{estimated_cost:.2f}円")
return 0
# =============================================================================
# コマンド: dialogue
# =============================================================================
def cmd_dialogue(args):
"""JSON台本から掛け合い音声を生成"""
api_key = get_api_key()
client = genai.Client(api_key=api_key)
input_path = args.input
output_dir = Path(args.output) if args.output else Path(input_path).parent / "output"
combine = args.combine
pause_same = args.pause_same
pause_diff = args.pause_different
# 台本を読み込み
print(f"台本を読み込み中: {input_path}")
with open(input_path, "r", encoding="utf-8") as f:
dialogue_data = json.load(f)
title = dialogue_data.get("title", "Untitled")
speakers = dialogue_data.get("speakers", {})
dialogue = dialogue_data.get("dialogue", [])
print(f"タイトル: {title}")
print(f"話者数: {len(speakers)}")
print(f"セリフ数: {len(dialogue)}")
print()
# 出力ディレクトリ作成
output_dir.mkdir(parents=True, exist_ok=True)
print(f"出力先: {output_dir}")
print()
# 各セリフを音声生成
generated_files = []
total_cost = 0
for i, line in enumerate(dialogue, start=1):
speaker_id = line["speaker"]
text = line["text"]
speaker_info = speakers.get(speaker_id, {})
voice = speaker_info.get("voice", DEFAULT_VOICE)
speaker_name = speaker_info.get("name", speaker_id)
print(f"[{i}/{len(dialogue)}] {speaker_name}({voice})")
print(f" テキスト: {text[:30]}{'...' if len(text) > 30 else ''}")
try:
audio_data = generate_audio(client, text, voice)
filename = f"{i:02d}_{voice.lower()}.wav"
output_path = output_dir / filename
save_wav(audio_data, str(output_path))
duration = get_audio_duration(audio_data)
file_size = output_path.stat().st_size
cost = duration * COST_PER_SECOND_YEN
total_cost += cost
print(f" 保存: {filename} ({file_size:,} bytes, {duration:.1f}秒)")
generated_files.append({
"index": i,
"speaker": speaker_name,
"voice": voice,
"file": filename,
"size": file_size,
"duration": duration,
"text": text
})
except Exception as e:
print(f" エラー: {e}")
continue
# メタデータを保存
total_duration = sum(f["duration"] for f in generated_files)
total_size = sum(f["size"] for f in generated_files)
metadata = {
"title": title,
"speakers": speakers,
"files": generated_files,
"total_duration": total_duration,
"total_size": total_size,
"generated_at": datetime.now().isoformat()
}
metadata_path = output_dir / "metadata.json"
with open(metadata_path, "w", encoding="utf-8") as f:
json.dump(metadata, f, ensure_ascii=False, indent=2)
# 結果サマリー
print()
print("=" * 50)
print("生成完了")
print("=" * 50)
print(f"成功: {len(generated_files)}/{len(dialogue)} ファイル")
print(f"合計時間: {total_duration:.1f}秒")
print(f"合計サイズ: {total_size:,} bytes")
print(f"コスト見積: 約{total_cost:.2f}円")
print(f"メタデータ: {metadata_path}")
# 結合オプション
if combine and len(generated_files) > 0:
print()
print("-" * 50)
print("音声ファイルを結合中...")
combined_path = output_dir / "combined.wav"
combine_files(
metadata_path=str(metadata_path),
output_path=str(combined_path),
pause_same=pause_same,
pause_diff=pause_diff,
update_metadata=False # dialogueでは生成直後なので更新不要
)
return 0
def combine_files(metadata_path: str, output_path: str,
pause_same: float = 0.3, pause_diff: float = 0.6,
update_metadata: bool = True):
"""メタデータに基づいて音声ファイルを結合
Args:
metadata_path: metadata.jsonのパス
output_path: 出力WAVファイルのパス
pause_same: 同一話者間のポーズ秒数
pause_diff: 話者交代時のポーズ秒数
update_metadata: Trueの場合、実際のファイル情報でmetadata.jsonを更新
"""
with open(metadata_path, 'r', encoding='utf-8') as f:
metadata = json.load(f)
files = metadata['files']
base_dir = Path(metadata_path).parent
combined_audio = b''
prev_speaker = None
total_pause_time = 0
total_audio_duration = 0
for i, file_info in enumerate(files):
file_path = base_dir / file_info['file']
speaker = file_info.get('voice', '') # voiceで話者を判定
audio_data, params = read_wav(str(file_path))
# 実際のファイルから duration と size を計算
actual_duration = len(audio_data) / (params['frame_rate'] * params['sample_width'])
actual_size = file_path.stat().st_size
# metadata を更新
if update_metadata:
file_info['duration'] = actual_duration
file_info['size'] = actual_size
total_audio_duration += actual_duration
if i > 0:
if speaker == prev_speaker:
pause_duration = pause_same
else:
pause_duration = pause_diff
silence = create_silence(pause_duration, params['frame_rate'])
combined_audio += silence
total_pause_time += pause_duration
combined_audio += audio_data
prev_speaker = speaker
# 保存
save_wav(combined_audio, output_path,
sample_rate=params['frame_rate'],
sample_width=params['sample_width'],
channels=params['channels'])
# metadata.json を更新
if update_metadata:
metadata['total_duration'] = total_audio_duration
metadata['total_size'] = sum(f['size'] for f in files)
metadata['last_combined_at'] = datetime.now().isoformat()
with open(metadata_path, 'w', encoding='utf-8') as f:
json.dump(metadata, f, ensure_ascii=False, indent=2)
final_duration = total_audio_duration + total_pause_time
print(f"結合完了: {output_path}")
print(f" 音声部分: {total_audio_duration:.1f}秒")
print(f" ポーズ部分: {total_pause_time:.1f}秒")
print(f" 合計: {final_duration:.1f}秒")
if update_metadata:
print(f" metadata.json: 更新済み")
# =============================================================================
# コマンド: combine
# =============================================================================
def cmd_combine(args):
"""既存の音声ファイルを結合"""
metadata_path = args.metadata
# -o はディレクトリ指定(dialogueと統一)
output_dir = Path(args.output) if args.output else Path(metadata_path).parent
output_path = str(output_dir / "combined.wav")
print(f"メタデータ: {metadata_path}")
print(f"出力先: {output_path}")
print(f"同一話者ポーズ: {args.pause_same}秒")
print(f"話者交代ポーズ: {args.pause_different}秒")
print()
combine_files(
metadata_path=metadata_path,
output_path=output_path,
pause_same=args.pause_same,
pause_diff=args.pause_different
)
return 0
# =============================================================================
# コマンド: voices
# =============================================================================
def cmd_voices(args):
"""利用可能なボイス一覧を表示"""
print("利用可能なボイス一覧")
print("=" * 50)
print()
print("【日本語推奨】")
for voice in AVAILABLE_VOICES:
mark = "★" if voice in ["Kore", "Charon"] else " "
print(f" {mark} {voice}")
print()
print("★ = 掛け合い推奨ペア")
print()
print("詳細は Day 3 記事を参照してください")
return 0
# =============================================================================
# ユーティリティ
# =============================================================================
def get_api_key() -> str:
"""APIキーを取得"""
api_key = os.environ.get("GOOGLE_API_KEY") or os.environ.get("GEMINI_API_KEY")
if not api_key:
print("エラー: GOOGLE_API_KEY または GEMINI_API_KEY 環境変数が設定されていません")
sys.exit(1)
return api_key
# =============================================================================
# メイン
# =============================================================================
def main():
parser = argparse.ArgumentParser(
description="Gemini TTS 音声生成ツール",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
使用例:
# 単一テキストの音声生成
python gemini_tts.py text "こんにちは、今日も良い天気ですね。" -o hello.wav
# ボイスを指定
python gemini_tts.py text "説明します。" --voice Charon -o explain.wav
# JSON台本から掛け合い音声を生成
python gemini_tts.py dialogue script.json -o output/
# 結合済み音声も同時に生成
python gemini_tts.py dialogue script.json -o output/ --combine
# 既存ファイルを結合
python gemini_tts.py combine output/metadata.json
# 利用可能なボイス一覧
python gemini_tts.py voices
"""
)
subparsers = parser.add_subparsers(dest="command", help="コマンド")
# text コマンド
text_parser = subparsers.add_parser("text", help="単一テキストの音声生成")
text_parser.add_argument("text", help="読み上げるテキスト")
text_parser.add_argument("-o", "--output", help="出力ファイル(デフォルト: output.wav)")
text_parser.add_argument("--voice", default=DEFAULT_VOICE,
help=f"ボイス名(デフォルト: {DEFAULT_VOICE})")
text_parser.set_defaults(func=cmd_text)
# dialogue コマンド
dialogue_parser = subparsers.add_parser("dialogue", help="JSON台本から掛け合い音声を生成")
dialogue_parser.add_argument("input", help="入力JSONファイル")
dialogue_parser.add_argument("-o", "--output", help="出力ディレクトリ")
dialogue_parser.add_argument("--combine", action="store_true",
help="結合済み音声も生成")
dialogue_parser.add_argument("--pause-same", type=float, default=0.3,
help="同一話者間ポーズ秒数(デフォルト: 0.3)")
dialogue_parser.add_argument("--pause-different", type=float, default=0.6,
help="話者交代ポーズ秒数(デフォルト: 0.6)")
dialogue_parser.set_defaults(func=cmd_dialogue)
# combine コマンド
combine_parser = subparsers.add_parser("combine", help="既存の音声ファイルを結合")
combine_parser.add_argument("metadata", help="metadata.jsonのパス")
combine_parser.add_argument("-o", "--output", help="出力ディレクトリ")
combine_parser.add_argument("--pause-same", type=float, default=0.3,
help="同一話者間ポーズ秒数(デフォルト: 0.3)")
combine_parser.add_argument("--pause-different", type=float, default=0.6,
help="話者交代ポーズ秒数(デフォルト: 0.6)")
combine_parser.set_defaults(func=cmd_combine)
# voices コマンド
voices_parser = subparsers.add_parser("voices", help="利用可能なボイス一覧を表示")
voices_parser.set_defaults(func=cmd_voices)
args = parser.parse_args()
if not args.command:
parser.print_help()
return 1
return args.func(args)
if __name__ == "__main__":
sys.exit(main())
Discussion