forked from pndurette/gTTS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgtts-cli.py
executable file
·52 lines (42 loc) · 1.68 KB
/
gtts-cli.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#! /usr/bin/python
from __future__ import print_function
from gtts import gTTS
from gtts import __version__
import sys
import argparse
import os
import codecs
def languages():
"""Sorted pretty printed string of supported languages"""
return ", ".join(sorted("{}: '{}'".format(gTTS.LANGUAGES[k], k) for k in gTTS.LANGUAGES))
# Args
desc = "Creates an mp3 file from spoken text via the Google Text-to-Speech API ({v})".format(v=__version__)
parser = argparse.ArgumentParser(description=desc, formatter_class=argparse.RawTextHelpFormatter)
text_group = parser.add_mutually_exclusive_group(required=True)
text_group.add_argument('text', nargs='?', help="text to speak")
text_group.add_argument('-f', '--file', help="file to speak")
parser.add_argument("-o", '--destination', help="destination mp3 file", action='store')
parser.add_argument('-l', '--lang', default='en', help="ISO 639-1/IETF language tag to speak in:\n" + languages())
parser.add_argument('--slow', action="store_true", help="slower read speed")
parser.add_argument('--debug', action="store_true")
args = parser.parse_args()
try:
if args.text:
if args.text == "-":
text = sys.stdin.read()
else:
text = args.text.decode('utf-8')
else:
with codecs.open(args.file, "r", "utf-8") as f:
text = f.read()
# TTSTF (Text to Speech to File)
tts = gTTS(text=text, lang=args.lang, slow=args.slow, debug=args.debug)
if args.destination:
tts.save(args.destination)
else:
tts.write_to_fp(os.fdopen(sys.stdout.fileno(), "wb"))
except Exception as e:
if args.destination:
print(str(e))
else:
print("ERROR: ", e, file=sys.stderr)