(137)【Google Cloud TTS #4】WEBブラウザから実行

投稿者: | 2026年3月25日

28 views

【0】連載内容

(134)【Google Cloud TTS #1】子どもの英会話学習教材を作りたい!
(135)【Google Cloud TTS #2】Google Cloud側の準備作業
(136)【Google Cloud TTS #3】自前サーバー側の準備作業(Ubuntu24)
(137)【Google Cloud TTS #4】WEBブラウザから実行 ←今回はココ
(138)【Google Cloud TTS #5】話す速度をゆっくりに
(139)【Google Cloud TTS #6】声の大きさ、声の高さを変える。
(140)【Google Cloud TTS #7】Webブラウザ上で話者(Voice)を指定可能に
(141)【Google Cloud TTS #8】二人以上の会話を入力可能に
(142)【Google Cloud TTS #9】英会話教材を作る。(一先ず完結)

【1】やりたいこと

(135)【Google Cloud TTS #2】Google Cloud側の準備作業 では、Cloud側の設定を完了させた。

(136)【Google Cloud TTS #3】自前サーバー側の準備作業(Ubuntu24) では、自前サーバ側の環境を作った。

今回は…
外部パソコンから Webブラウザで自前サーバにリクエストを送信し、自前サーバが Google Cloudに TTS実行をリクエストする Webアプリを作りたい。

仕様は以下の通り。
(A) Webページは Python CGI実装する。 → index.py を作る。
(B) TTS実行プログラムは、index.py から import される形にする。(shell実行ではない)
(C) Webページ一式は /opt/webts/www に設置する。
(D) これに伴い、MP3の出力先を webtts/output から webtts/www/sound に変更する。

以下、これを粛々と進めたい。

【2】やってみる

(1) MP3の出力先を webtts/output から webtts/www/sound に変更する。

# www, www/sound ディレクトリを作成
mkdir -p /opt/webtts/www/sound

# SGIDを設定して、作成されるファイルが www-data グループになるようにする
chmod 2770 /opt/webtts/www/sound

# 前回の投稿で作成した MP3出力先ディレクトリを削除
rm -rf /opt/webtts/output

(2) Webページは Python CGI実装する。(index.pyを作る)

初版なので、まずはミニマム実装してみる。
後で機能を追加して行けばよろしいか。

index.py

#!/opt/webtts/myenv/bin/python
import cgi
import os
import sys
from datetime import datetime

# 自作モジュールのパスを通す
sys.path.append('/opt/webtts/src')
import my_ggtts 

# デバッグ用(エラー時に詳細をブラウザに表示)
import cgitb
cgitb.enable()

# フォームデータの取得
form = cgi.FieldStorage()
input_text = form.getvalue("text", "")
html_sound = ""

#-----------------------------------------------------------------------
# フォームにテキストが入力されていれば TTSを実行する。
if input_text:
    # MP3ファイル名を作る。
    timestamp = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
    filename = f"sound-{timestamp}.mp3"
    try:
        my_ggtts.generate_voice(input_text, filename)
        # ブラウザからアクセス可能な MP3ファイルの URLパス
        audio_url  = f"/webtts/sound/{filename}"
        html_sound = f"""
            <hr>
            <h3>生成結果:</h3>
            <audio controls autoplay>
                <source src="{audio_url}?t={os.path.getmtime('/opt/webtts/www/sound/'+filename)}" type="audio/mpeg">
                お使いのブラウザはaudio要素をサポートしていません。
            </audio>
        """
    except Exception as e:
        print(f"<p style='color:red;'>エラー発生: {e}</p>")

#-----------------------------------------------------------------------
# HTTPヘッダーの出力
print("Content-Type: text/html; charset=utf-8\n")

#-----------------------------------------------------------------------
# HTMLの出力
print(f"""
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>Google Cloud TTS Demo</title>
</head>
<body>
    <h1>Text to Speech</h1>
    <form method="POST">
        <textarea name="text" rows="4" cols="50" placeholder="喋らせたい文字を入力...">{input_text}</textarea><br>
        <button type="submit">音声を生成</button>
    </form>
    {html_sound}
</body></html>
""")
# index.py に実行属性を追加する。
chmod +x /opt/webtts/src/index.py

my_ggtts.py

import os
from google.cloud import texttospeech

# Text-to-Speech API 鍵ファイルの絶対パス
KEY_PATH = "/opt/webtts/auth/key.json"
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = KEY_PATH

#-----------------------------------------------------------------------
# 引数:   text(合成する文字), filename(保存ファイル名)
# 戻り値: 保存されたファイルの絶対パス
def generate_voice( text, filename ):
    client = texttospeech.TextToSpeechClient()
    synthesis_input = texttospeech.SynthesisInput(text=text)
    
    # 音声設定
    voice = texttospeech.VoiceSelectionParams(
        language_code="en-US", name="en-US-Chirp3-HD-Rasalgethi")
    audio_config = texttospeech.AudioConfig(
        audio_encoding=texttospeech.AudioEncoding.MP3)
    
    # TS実行
    response = client.synthesize_speech(
        input=synthesis_input, voice=voice, audio_config=audio_config)
    
    # MP3ファイル出力
    output_path = os.path.join("/opt/webtts/www/sound", filename)
    with open(output_path, "wb") as out:
        out.write(response.audio_content)
    
    return output_path

(3) Webページ一式は /opt/webts/www に設置する。

HTTPサーバ(Apach2.4)の設定を追加する。
http://{IPアドレス}/webtts
で index.py にアクセスできるように設定する。

# webttsアプリ用に Apacheの設定ファイルを追加する。(偶然同名のファイルがあれば名前を変えること)
sudo vi /etc/apache2/sites-available/webtts.conf

confファイルの中身は以下の通り。

Alias /webtts /opt/webtts/www

<Directory "/opt/webtts/www">
    Options +ExecCGI +FollowSymLinks
    AddHandler cgi-script .py
    Require all granted
</Directory>
# 設定ファイルを有効化する。
sudo a2ensite webtts.conf

# Apachを再起動する。
sudo systemctl reload apache2

# 起動後の状態を確認する。
sudo systemctl status apache2

できた!

一先ずミニマム実装版が完成した。
英文テキストを入力すると、音声ファイル化してくれる。
それだけの Webアプリです。

【3】次にやりたいこと

・二人以上の会話を入力可能にする。
 → (音声キャラクター、英文テキスト)をセットとし、複数セットを順番に TTS処理し、一つのMP3ファイルに結合する。

・しゃべる速度を遅くする。
  1.0倍だと英会話初心者の教材としては速過ぎて厳しい…


アクセス数(直近7日): ※試験運用中、BOT除外簡易実装済
  • 2026-03-31: 0回
  • 2026-03-30: 1回
  • 2026-03-29: 2回
  • 2026-03-28: 6回
  • 2026-03-27: 6回
  • 2026-03-26: 6回
  • 2026-03-25: 11回
  • コメントを残す

    メールアドレスが公開されることはありません。 が付いている欄は必須項目です