-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
play_audio.py
73 lines (68 loc) · 2.91 KB
/
play_audio.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
72
73
import threading
import pychromecast
import logging
import time
class PlayAudio(threading.Thread):
__repeat = 3
__sleep = 5
__config: dict = {}
__logger: logging.Logger
__audio_file: str
__stop_event: threading.Event
def __init__(self, audio_file: str, repeat: int, sleep: int, config: dict, logger: logging.Logger):
super(PlayAudio, self).__init__()
self.__repeat = repeat
self.__sleep = sleep
self.__config = config
self.__logger = logger
self.__audio_file = audio_file
self.__stop_event = threading.Event()
def stop(self):
self.__stop_event.set()
def run(self):
try:
chromecast, browser = pychromecast.get_listed_chromecasts(
[self.__config["CAST_DEVICE_NAME"]],
tries=3,
timeout=self.__sleep,
discovery_timeout=self.__sleep
)
if len(chromecast) > 0:
cast = chromecast[0]
self.__logger.debug("Cast info: %s", cast.cast_info)
cast.wait(self.__sleep)
self.__logger.debug("Cast status: %s", cast.status)
mediaController = cast.media_controller
self.__logger.info(
"[%s]: Playing on %s %s times repeat",
self.__audio_file,
self.__config["CAST_DEVICE_NAME"],
self.__repeat
)
while self.__repeat > 0:
if self.__stop_event.is_set():
self.__logger.info(
"[%s]: Stopped play audio with %s times repeat remaining", self.__audio_file, self.__repeat)
cast.disconnect()
browser.stop_discovery()
break
mediaController.play_media(
f"{self.__config['AUDIO_BASE_URL']}/{self.__audio_file}", "audio/mp3")
mediaController.block_until_active(self.__sleep)
self.__repeat = self.__repeat - 1
self.__logger.info(
"[%s]: Play times remaining: %s", self.__audio_file, self.__repeat)
if self.__repeat > 0:
self.__logger.info("[%s]: Wating for %s second before repeat",
self.__audio_file, self.__sleep)
time.sleep(self.__sleep)
self.__logger.debug("MediaControler status: %s",
mediaController.status)
cast.disconnect()
browser.stop_discovery()
else:
self.__logger.info(
"[%s]: No device to play audio", self.__audio_file)
except Exception as e:
self.__logger.exception(
"[%s]: Got exception when play audio", self.__audio_file, e)