🎬

AIで作る業務動画 Day 4|Gemini TTSで掛け合い音声を作る

に公開

今日のゴール

複数のボイスを使い分けて、掛け合い形式(対話形式)のナレーション音声を生成する。


昨日までに Gemini TTS API のボイスプリセットとスタイル制御を検証した。今日は、二人の話者が会話する「掛け合い音声」に挑戦する。

業務動画では、解説者と質問者の対話形式にすると理解しやすくなる。一人で淡々と説明するより、「それってどういうことですか?」と質問が入ることで、視聴者も一緒に考えやすくなる。

前提条件

  • Day 2-3の環境が構築済み(Gemini TTS APIが動作する状態)
  • google-genai 1.56.0 以上

ボイスの役割分担

対話に向いたボイスの選定

Day 3 で検証した12種類のボイスから、掛け合いに適した組み合わせを選んだ。

役割 ボイス 理由
解説者(先生役) Kore 知的で落ち着いた女性声
質問者(生徒役) Charon 説明調の男性声、対比がつく

声質の対比が大事。同じような声だと誰が話しているかわからなくなる。Kore(女性的・遅め)と Charon(男性的・速め)は明確に区別できる。

ベスト3の組み合わせ

検証した中で、特に相性が良かった組み合わせは以下の通り。

組み合わせ 用途 特徴
Kore + Charon 解説動画・研修 知的×説明調、最も対比が明確
Sulafat + Puck カジュアル動画 温かみ×明るさ、親しみやすい
Gacrux + Aoede ビジネス動画 重厚×さわやか、ゆったり進行

台本フォーマット

JSON形式で管理

複数の話者がいる台本は、JSON形式で管理すると処理しやすい。

{
  "title": "動画制作パイプラインの紹介",
  "speakers": {
    "A": { "name": "解説者", "voice": "Kore" },
    "B": { "name": "質問者", "voice": "Charon" }
  },
  "dialogue": [
    { "speaker": "A", "text": "今日は、AIを使った動画制作の流れについてお話しします。" },
    { "speaker": "B", "text": "動画制作って難しそうですね。プログラミングの知識がなくても大丈夫ですか?" },
    { "speaker": "A", "text": "はい、基本的な手順を覚えれば、非エンジニアの方でも作成できます。" }
  ]
}

台本設計のコツ

ポイント 推奨
セリフの長さ 解説者: 30〜60文字、質問者: 15〜30文字
質問の入れ方 「なるほど」「つまり」で話を整理
1セリフ 2文以内が聞きやすい

連続音声生成スクリプト

JSON台本から連続で音声を生成するスクリプトを作成した。

使い方

python generate_dialogue_audio.py dialogue_sample.json

出力例

台本を読み込み中: dialogue_sample.json
タイトル: 動画制作パイプラインの紹介
話者数: 2
セリフ数: 7
出力先: output

[1/7] 解説者(Kore)
  テキスト: 今日は、AIを使った動画制作の流れについてお話しします。
  保存: 01_kore.wav (223,290 bytes, 4.7秒)

[2/7] 質問者(Charon)
  テキスト: 動画制作って難しそうですね。...
  保存: 02_charon.wav (277,050 bytes, 5.8秒)

...

==================================================
生成完了
==================================================
成功: 7/7 ファイル
合計時間: 38.0秒
合計サイズ: 1,822,230 bytes

7セリフで合計38秒の音声が生成された。ファイルは連番で出力されるので、後から結合しやすい。

スクリプトの主要部分

def generate_audio(client, text: str, voice: str) -> bytes:
    """指定したボイスで音声を生成"""
    response = client.models.generate_content(
        model="gemini-2.5-flash-preview-tts",
        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
                    )
                )
            )
        )
    )
    return response.candidates[0].content.parts[0].inline_data.data

話者ごとに voice_name を切り替えるだけで、異なるボイスで音声が生成される。

音声の繋ぎ目・間の調整

ポーズ(間)の重要性

生成された音声ファイルをそのまま繋げると、不自然になる。話者が交代するときには「間」が必要。

推奨設定

3パターンのポーズ設定で結合を試し、聞き比べた。

パターン 同一話者間 話者交代 印象
短め 0.2秒 0.4秒 せわしない
標準 0.3秒 0.6秒 自然
長め 0.5秒 0.8秒 間延び気味

標準設定(0.3秒/0.6秒)が業務動画に最適という結論に至った。話者交代時は同一話者間の約2倍のポーズが自然に聞こえる。

結合スクリプト

python combine_dialogue_audio.py output/metadata.json

ポーズ設定はオプションで変更できる。

# 研修動画向け(ゆったり)
python combine_dialogue_audio.py output/metadata.json --pause-same 0.4 --pause-different 0.7

結合結果

項目 値
音声部分 38.0秒
ポーズ部分 3.6秒
合計 41.6秒

7セリフの掛け合いが約42秒の一つのファイルにまとまった。

今日の成果物

  • 複数ボイス役割分担設計
  • JSON形式の台本サンプル
  • 連続音声生成スクリプト(generate_dialogue_audio.py)
  • 音声結合スクリプト(combine_dialogue_audio.py)
  • 掛け合い音声サンプル(7セリフ、約42秒)

生成したファイル

ファイル 話者 長さ
01_kore.wav 解説者(Kore) 4.7秒
02_charon.wav 質問者(Charon) 5.8秒
03_kore.wav 解説者(Kore) 4.8秒
04_charon.wav 質問者(Charon) 3.0秒
05_kore.wav 解説者(Kore) 8.7秒
06_charon.wav 質問者(Charon) 4.3秒
07_kore.wav 解説者(Kore) 6.7秒
combined_default.wav 結合済み 41.6秒

検証環境

項目 バージョン
OS Windows 11 Pro
Python 3.12.10
google-genai 1.56.0
検証日 2026-01-02
台本フォーマット(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": "その通りです。一度パイプラインを構築すれば、台本を変えるだけで新しい動画を作れます。"
    }
  ]
}
連続音声生成スクリプト(generate_dialogue_audio.py)
"""
Gemini TTS API - 掛け合い音声生成スクリプト
Day 4: 連続音声生成の実装

機能:
- JSON形式の台本を読み込み
- 各セリフを対応するボイスで音声生成
- 連番付きWAVファイルとして出力
"""

import os
import json
import wave
import argparse
from pathlib import Path
from google import genai
from google.genai import types


def load_dialogue(json_path: str) -> dict:
    """JSON形式の台本を読み込む"""
    with open(json_path, "r", encoding="utf-8") as f:
        return json.load(f)


def generate_audio(client: genai.Client, text: str, voice: str) -> bytes:
    """
    Gemini TTS APIで音声を生成

    Args:
        client: Gemini APIクライアント
        text: 読み上げるテキスト
        voice: ボイス名(Kore, Charon等)

    Returns:
        RAW PCM音声データ(16bit, 24kHz, mono)
    """
    response = client.models.generate_content(
        model="gemini-2.5-flash-preview-tts",
        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


def save_wav(audio_data: bytes, output_path: str):
    """RAW PCMデータをWAVファイルとして保存"""
    with wave.open(output_path, "wb") as wav_file:
        wav_file.setnchannels(1)         # モノラル
        wav_file.setsampwidth(2)         # 16bit = 2 bytes
        wav_file.setframerate(24000)     # 24kHz
        wav_file.writeframes(audio_data)


def main():
    parser = argparse.ArgumentParser(
        description="JSON台本から掛け合い音声を生成"
    )
    parser.add_argument(
        "input",
        help="入力JSONファイルのパス"
    )
    parser.add_argument(
        "-o", "--output-dir",
        default=None,
        help="出力ディレクトリ(デフォルト: 入力ファイルと同じ場所にoutput/を作成)"
    )
    args = parser.parse_args()

    # 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 環境変数が設定されていません")
        return 1

    # 台本を読み込み
    print(f"台本を読み込み中: {args.input}")
    dialogue_data = load_dialogue(args.input)

    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)}")

    # 出力ディレクトリを決定
    if args.output_dir:
        output_dir = Path(args.output_dir)
    else:
        output_dir = Path(args.input).parent / "output"

    output_dir.mkdir(parents=True, exist_ok=True)
    print(f"出力先: {output_dir}")

    # クライアントを初期化
    client = genai.Client(api_key=api_key)

    # 各セリフを音声生成
    generated_files = []

    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", "Kore")
        speaker_name = speaker_info.get("name", speaker_id)

        print(f"\n[{i}/{len(dialogue)}] {speaker_name}({voice})")
        print(f"  テキスト: {text[:30]}{'...' if len(text) > 30 else ''}")

        try:
            # 音声生成
            audio_data = generate_audio(client, text, voice)

            # ファイル名: 01_kore.wav, 02_charon.wav, ...
            filename = f"{i:02d}_{voice.lower()}.wav"
            output_path = output_dir / filename

            # WAVファイルとして保存
            save_wav(audio_data, str(output_path))

            file_size = output_path.stat().st_size
            duration = file_size / (24000 * 2)  # 24kHz, 16bit

            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

    # 結果サマリーを出力
    print("\n" + "=" * 50)
    print("生成完了")
    print("=" * 50)
    print(f"成功: {len(generated_files)}/{len(dialogue)} ファイル")

    total_duration = sum(f["duration"] for f in generated_files)
    total_size = sum(f["size"] for f in generated_files)

    print(f"合計時間: {total_duration:.1f}秒")
    print(f"合計サイズ: {total_size:,} bytes")

    # メタデータをJSONで保存
    metadata_path = output_dir / "metadata.json"
    metadata = {
        "title": title,
        "speakers": speakers,
        "files": generated_files,
        "total_duration": total_duration,
        "total_size": total_size
    }

    with open(metadata_path, "w", encoding="utf-8") as f:
        json.dump(metadata, f, ensure_ascii=False, indent=2)

    print(f"\nメタデータ: {metadata_path}")

    return 0


if __name__ == "__main__":
    exit(main())
音声結合スクリプト(combine_dialogue_audio.py)
"""
掛け合い音声の結合スクリプト
Day 4: 音声の繋ぎ目・間の調整検証

機能:
- 複数のWAVファイルを結合
- 話者交代時に適切な間(ポーズ)を挿入
- 同一話者の連続発言は短い間
"""

import os
import json
import wave
import struct
import argparse
from pathlib import Path


def create_silence(duration_sec: float, sample_rate: int = 24000) -> bytes:
    """
    無音データを生成

    Args:
        duration_sec: 無音の長さ(秒)
        sample_rate: サンプルレート(Hz)

    Returns:
        無音のPCMデータ
    """
    num_samples = int(duration_sec * sample_rate)
    # 16bit signed integer, little endian
    return struct.pack('<' + 'h' * num_samples, *([0] * num_samples))


def read_wav(file_path: str) -> tuple[bytes, dict]:
    """
    WAVファイルを読み込む

    Returns:
        (PCMデータ, パラメータ辞書)
    """
    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 write_wav(file_path: str, audio_data: bytes, params: dict):
    """WAVファイルを書き出す"""
    with wave.open(file_path, 'wb') as wav:
        wav.setnchannels(params['channels'])
        wav.setsampwidth(params['sample_width'])
        wav.setframerate(params['frame_rate'])
        wav.writeframes(audio_data)


def combine_dialogue(
    metadata_path: str,
    output_path: str,
    pause_same_speaker: float = 0.3,
    pause_different_speaker: float = 0.6
):
    """
    メタデータに基づいて音声ファイルを結合

    Args:
        metadata_path: metadata.jsonのパス
        output_path: 出力ファイルパス
        pause_same_speaker: 同一話者間のポーズ(秒)
        pause_different_speaker: 話者交代時のポーズ(秒)
    """
    # メタデータを読み込み
    with open(metadata_path, 'r', encoding='utf-8') as f:
        metadata = json.load(f)

    files = metadata['files']
    base_dir = Path(metadata_path).parent

    print(f"結合するファイル数: {len(files)}")
    print(f"同一話者間ポーズ: {pause_same_speaker}秒")
    print(f"話者交代ポーズ: {pause_different_speaker}秒")
    print()

    combined_audio = b''
    prev_speaker = None
    total_pause_time = 0

    for i, file_info in enumerate(files):
        file_path = base_dir / file_info['file']
        speaker = file_info['speaker']

        # 音声データを読み込み
        audio_data, params = read_wav(str(file_path))

        # 最初のファイル以外はポーズを挿入
        if i > 0:
            if speaker == prev_speaker:
                pause_duration = pause_same_speaker
                pause_type = "同一話者"
            else:
                pause_duration = pause_different_speaker
                pause_type = "話者交代"

            silence = create_silence(pause_duration, params['frame_rate'])
            combined_audio += silence
            total_pause_time += pause_duration

            print(f"[{i+1}/{len(files)}] {file_info['file']} ({file_info['duration']:.1f}秒)")
            print(f"         ↑ {pause_type}ポーズ: {pause_duration}秒")
        else:
            print(f"[{i+1}/{len(files)}] {file_info['file']} ({file_info['duration']:.1f}秒)")

        combined_audio += audio_data
        prev_speaker = speaker

    # 結合した音声を保存
    write_wav(output_path, combined_audio, params)

    # 結果を表示
    total_audio_duration = metadata['total_duration']
    final_duration = total_audio_duration + total_pause_time

    print()
    print("=" * 50)
    print("結合完了")
    print("=" * 50)
    print(f"音声部分: {total_audio_duration:.1f}秒")
    print(f"ポーズ部分: {total_pause_time:.1f}秒")
    print(f"合計: {final_duration:.1f}秒")
    print(f"出力: {output_path}")

    return {
        'audio_duration': total_audio_duration,
        'pause_duration': total_pause_time,
        'total_duration': final_duration
    }


def main():
    parser = argparse.ArgumentParser(
        description="掛け合い音声ファイルを結合"
    )
    parser.add_argument(
        "metadata",
        help="metadata.jsonのパス"
    )
    parser.add_argument(
        "-o", "--output",
        default=None,
        help="出力ファイルパス(デフォルト: combined.wav)"
    )
    parser.add_argument(
        "--pause-same",
        type=float,
        default=0.3,
        help="同一話者間のポーズ秒数(デフォルト: 0.3)"
    )
    parser.add_argument(
        "--pause-different",
        type=float,
        default=0.6,
        help="話者交代時のポーズ秒数(デフォルト: 0.6)"
    )
    args = parser.parse_args()

    # 出力パスを決定
    if args.output:
        output_path = args.output
    else:
        output_path = str(Path(args.metadata).parent / "combined.wav")

    # 結合実行
    result = combine_dialogue(
        args.metadata,
        output_path,
        pause_same_speaker=args.pause_same,
        pause_different_speaker=args.pause_different
    )

    return 0


if __name__ == "__main__":
    exit(main())

明日のテーマ: Phase 1の総まとめ。台本から音声を自動生成するスクリプトを完成させ、これまでの検証結果を振り返る。


シリーズを追いかける

→ 著者ページ(Zenn)

Discussion