This repository has been archived by the owner on Aug 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
/
main.py
71 lines (59 loc) · 1.94 KB
/
main.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from flask import Flask, request
import pychromecast
import logging
import os
from gtts import gTTS
from slugify import slugify
from pathlib import Path
from urllib.parse import urlparse
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
chromecast_name = os.getenv('GRP_NAME') #set envar to match your speaker or group name
app = Flask(__name__)
logging.info("Starting up chromecasts")
chromecasts, _ = pychromecast.get_chromecasts()
logging.info("Searching for {}".format(chromecast_name))
cast = next(cc for cc in chromecasts if cc.cast_info.friendly_name == chromecast_name)
def play_tts(text, lang='en', slow=False):
tts = gTTS(text=text, lang=lang, slow=slow)
filename = slugify(text+"-"+lang+"-"+str(slow)) + ".mp3"
path = "/static/cache/"
cache_filename = os.path.dirname(__file__) + path + filename
tts_file = Path(cache_filename)
if not tts_file.is_file():
logging.info(tts)
tts.save(cache_filename)
urlparts = urlparse(request.url)
mp3_url = "http://" +urlparts.netloc + path + filename
logging.info(mp3_url)
play_mp3(mp3_url)
def play_mp3(mp3_url):
print(mp3_url)
cast.wait()
mc = cast.media_controller
mc.play_media(mp3_url, 'audio/mp3')
mc.block_until_active()
@app.route('/static/<path:path>')
def send_static(path):
return send_from_directory('static', path)
@app.route('/play/<filename>')
def play(filename):
urlparts = urlparse(request.url)
mp3 = Path(os.path.dirname(__file__) + "/static/" + filename)
if mp3.is_file():
play_mp3("http://"+urlparts.netloc+"/static/"+filename)
return filename
else:
return "False"
@app.route('/say/')
def say():
text = request.args.get("text")
lang = request.args.get("lang")
if not text:
return False
if not lang:
lang = "en"
play_tts(text, lang=lang)
return text
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0')