edge_tts_sample.py ダウンロード/コピー
edge_tts_sample.py
edge_tts_sample.py
1"""
2概要:
3 edge-ttsを用いてテキストを音声合成し再生するサンプルスクリプトです。
4
5詳細説明:
6 コマンドライン引数としてテキストまたはテキストファイルのパスを受け取り、
7 edge-ttsを使用して音声を生成し、生成されたMP3ファイルをOSの既定のアプリで再生します。
8
9関連リンク:
10 edge_tts_sample_usage
11"""
12
13import sys
14import os
15import asyncio
16import tempfile
17import subprocess
18
19import edge_tts
20
21
22VOICE = "ja-JP-NanamiNeural"
23
24
25async def speak(text):
26 """
27 概要:
28 与えられたテキストを音声に変換し、一時ファイルとして保存した後に再生します。
29
30 詳細説明:
31 edge-ttsライブラリを使用して指定されたテキストの音声を生成します。
32 音声は一時的なMP3ファイルに保存され、Windows、macOS、Linuxの環境に合わせて
33 デフォルトのプレイヤーで再生されます。
34
35 引数:
36 :param text: 読み上げる対象のテキスト。
37 :type text: str
38
39 戻り値:
40 :returns: なし。
41 :rtype: None
42
43 例外:
44 :raises Exception: 音声ファイルの再生中にエラーが発生した場合にコンソールに出力します。
45 """
46
47 with tempfile.NamedTemporaryFile(
48 suffix=".mp3",
49 delete=False
50 ) as f:
51
52 mp3file = f.name
53
54 communicate = edge_tts.Communicate(
55 text=text,
56 voice=VOICE
57 )
58
59 await communicate.save(mp3file)
60
61 try:
62 if sys.platform.startswith("win"):
63 os.startfile(mp3file)
64
65 elif sys.platform == "darwin":
66 subprocess.run(["open", mp3file])
67
68 else:
69 subprocess.run(["xdg-open", mp3file])
70
71 except Exception as e:
72 print(e)
73
74
75def main():
76 """
77 概要:
78 コマンドライン引数を処理し、音声合成と再生を実行します。
79
80 詳細説明:
81 コマンドライン引数が1つ未満の場合は使い方を表示して終了します。
82 引数が実在するファイルパスの場合はそのファイルの内容を読み込み、
83 そうでない場合は引数そのものをテキストとして扱います。
84 その後、speak関数を非同期実行して音声を再生します。
85
86 戻り値:
87 :returns: なし。
88 :rtype: None
89 """
90
91 if len(sys.argv) < 2:
92 print("Usage:")
93 print(' python edge_read.py "こんにちは"')
94 print(" python edge_read.py sample.txt")
95 sys.exit(1)
96
97 arg = sys.argv[1]
98
99 #
100 # 引数が実在するファイルなら内容を読む
101 #
102 if os.path.isfile(arg):
103
104 print(f"Read text file: {arg}")
105
106 with open(arg, encoding="utf-8") as f:
107 text = f.read()
108
109 #
110 # そうでなければ引数自身を読む
111 #
112 else:
113
114 print("Read text from command line")
115
116 text = arg
117
118 asyncio.run(speak(text))
119
120
121if __name__ == "__main__":
122 main()