Exemplo n.º 1
0
    def connect(self):
        self.connected = False

        if self.cast is None:
            device_name = self.config['name']
            casts, browser = pychromecast.get_listed_chromecasts(
                friendly_names=[device_name], tries=Chromecast.CAST_CONNECT_TRIES)
            stop_discovery(browser)
            if not casts:
                self.logger.debug(f'Device not found: {device_name}')
                return

            self.cast = casts[0]

        self.cast.wait(Chromecast.CAST_CONNECT_TIMEOUT)
        self.connected = self.cast.socket_client.is_connected
        if not self.connected:
            self.disconnect()
Exemplo n.º 2
0
def plugin(srv, item):
    srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__, item.service, item.target)

    message = item.message
    mime_type = item.config.get('mimetype', 'audio/mp3')  # Google translate emits mp3, NOTE Chromecast devices appear to  not care if incorrect
    base_url = item.config.get('baseuri', os.environ.get('GOOGLE_TRANSLATE_URL', 'https://translate.google.com/translate_tts?'))
    lang = item.config.get('lang', 'en')  # English

    # Generate a Google Translate (compatible) URL to generate TTS
    vars = {
        'q': message,
        'l': lang,
        'tl': lang,
        'client': 'tw-ob',
        'ttsspeed': 1,
        'total': 1,
        'ie': 'UTF-8',
        # looks like can get away with out 'textlen'
    }
    url = base_url + urlencode(vars)


    # TODO disable pychromecast library logging?
    import pychromecast  # Some plugin systems want lazy loading, defer import until about to use it

    chromecasts, browser  = pychromecast.get_listed_chromecasts(friendly_names=item.addrs)
    if not chromecasts:
        return False
    for cast in chromecasts:
        cast.wait()
        #srv.logging.debug("cast=%r", cast)
        """
        print('%r' % (cast.device.friendly_name,))
        print('%r' % (cast.socket_client.host,))
        """
        mc = cast.media_controller
        mc.play_media(url, content_type=mime_type)
        mc.block_until_active()
        mc.play()  # issue play, return immediately
        # TODO detect when play failed
        # if one end point works, but another fails is that a success or a failure?
        # What is an end point does NOT show up in list? i.e. len(item.addrs) > len(chromecasts)

    return True
Exemplo n.º 3
0
def castYoutube(cast_name, video_id):
    # Note: only compatible with ChromeCast devices
    print('Casting http://youtube.com/watch?v=' + video_id + ' to ' +
          cast_name)

    chromecasts = pychromecast.get_listed_chromecasts(
        friendly_names=[cast_name])
    if not chromecasts:
        print('No chromecast with name "{}" discovered'.format(cast_name))
        sys.exit(1)

    cast = chromecasts[0]
    # Start socket client's worker thread and wait for initial status update
    cast.wait()

    yt = YouTubeController()
    cast.register_handler(yt)
    yt.play_video(video_id)
    return True
def find_chromecast(known_hosts):
    print("Finding Chromecasts...")
    casts, browser = pychromecast.get_listed_chromecasts(
        friendly_names=["Living Room"], known_hosts=known_hosts)
    #print(casts)
    browser.stop_discovery()

    if len(casts) == 0:
        print("Living Room Chromecast not found.")
        exit(1)
    livingroom = casts[0]

    livingroom.wait()
    lr_info = livingroom.cast_info
    print("Connected to {} '{}' ({})".format(lr_info.model_name,
                                             lr_info.friendly_name,
                                             lr_info.host))

    return livingroom
    def new_function(self, message):
        device_name = message.data.get("Device", self._default_devicename())
        if not device_name:
            self.speak_dialog('no.device')
            return
        proper_name = self._devices_by_name.get(device_name)
        devices, browser = pychromecast.get_listed_chromecasts([proper_name])

        if not devices:
            self.speak_dialog("device.not.found", {"device": device_name})
            return

        device = list(devices)[0]
        device.wait()
        controller = device.media_controller
        controller.block_until_active(10)

        intent_function(self, message, controller)

        pychromecast.discovery.stop_discovery(browser)
        device.disconnect()
Exemplo n.º 6
0
def cc_stop(deviceName, sessionID):
    chromecasts, browser = pychromecast.get_listed_chromecasts(
        friendly_names=[deviceName])
    cast = chromecasts[0]
    cast.wait()
    mc = cast.media_controller
    time.sleep(2)
    if isinstance(mc.status.media_session_id, int):
        if mc.status.media_session_id == sessionID:
            mc.stop()
        else:
            LOG.info('Chromecast: sessionID did not match!')
        time.sleep(1)
    else:
        LOG.info('Chromecast: Nothing is Playing!')
    device_status = {}
    device_status['player_state'] = mc.status.player_state
    device_status['media_session_id'] = mc.status.media_session_id
    device_status['duration'] = mc.status.duration
    device_status['content_type'] = mc.status.content_type
    device_status['content_id'] = mc.status.content_id
    pychromecast.discovery.stop_discovery(browser)
    return device_status
Exemplo n.º 7
0
def Media_Stop():
    falcon_logger.info("Parando Cast")
    chromecasts, browser = pychromecast.get_listed_chromecasts(friendly_names=[config.CHROMECAST.NAME])

    if not chromecasts:
        msg="No encuentro el chromecast con nombre %s" % config.CHROMECAST.NAME
        falcon_logger.info(msg)
        return 9,msg

    cast = chromecasts[0]
    cast.wait()
    mc = cast.media_controller
    falcon_logger.info("Arrancando Stadnby")
    yt = YouTubeController()
    cast.register_handler(yt)
    retry=6
    while (retry):
        yt.play_video("9m6bfFWPIVE")
        if (mc.status.player_is_playing):
            break
        falcon_logger.info("No arranca, espero")
        time.sleep(2)
        retry-=1
Exemplo n.º 8
0
#!/usr/bin/python3
# Dumbest possible player. Lifted from: https://pypi.org/project/PyChromecast/
import pychromecast
import sys
import time

services, browser = pychromecast.discovery.discover_chromecasts()
pychromecast.discovery.stop_discovery(browser)
chromecasts, browser = pychromecast.get_listed_chromecasts(
    friendly_names=["Shower TV"])
cast = chromecasts[0]
cast.wait()
print(cast.device)
print(cast.status)
mc = cast.media_controller
mc.play_media(sys.argv[1], sys.argv[2])
mc.block_until_active()
print(mc.status)
pychromecast.discovery.stop_discovery(browser)
time.sleep(5)
print(mc.status)
time.sleep(15)
print(mc.status)
time.sleep(45)
print(mc.status)
Exemplo n.º 9
0
parser = argparse.ArgumentParser(prog="Meme Script")
parser.add_argument('--show_spoilers',
                    dest='show_spoilers',
                    action="store_true",
                    help="Queue up posts that are marked as spoilers")
parser.set_defaults(show_spoilers=False)
args = parser.parse_args()

CAST_NAME = "Living Room TV"

# Change to the video id of the YouTube video
# video id is the last part of the url http://youtube.com/watch?v=video_id
VIDEO_ID = "dQw4w9WgXcQ"
played_yet = False

chromecasts, browser = pychromecast.get_listed_chromecasts(
    friendly_names=[CAST_NAME])
cast = [x for x in chromecasts][0]
cast.wait()
yt = YouTubeController()
cast.register_handler(yt)
reddit = praw.Reddit(client_id=os.getenv("CLIENT_ID"),
                     client_secret=os.getenv("CLIENT_SECRET"),
                     username=os.getenv("REDDIT_USERNAME"),
                     password=os.getenv("REDDIT_PASSWORD"),
                     user_agent="youtube_haiku_bot")
for submission in reddit.subreddit('youtubehaiku').hot(limit=25):
    if submission.spoiler and not args.show_spoilers:
        continue
    link = submission.url
    VIDEO_ID = ""
    if "youtu.be" in link:
Exemplo n.º 10
0
import time
import pychromecast
import sys

# List chromecasts on the network, but don't connect
services, browser = pychromecast.discovery.discover_chromecasts()
# Shut down discovery
pychromecast.discovery.stop_discovery(browser)

for service in services:
    print(service)

# Discover and connect to chromecasts named Living Room
chromecasts, browser = pychromecast.get_listed_chromecasts(
    friendly_names=[sys.argv[1]])
[cc.device.friendly_name for cc in chromecasts]
print(chromecasts)
cast = list(chromecasts)[0]
# Start worker thread and wait for cast device to be ready
cast.wait()
print(cast.device)
print(cast.status)

mc = cast.media_controller
#mc.play_media('http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4', 'video/mp4')
mc.play_media(sys.argv[2], 'video/mp4')
mc.block_until_active()
print(mc.status)
mc.pause()
time.sleep(5)
mc.play()
Exemplo n.º 11
0
def cast_and_monitor(
        button,
        #source="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4",sourceaudiotype="vide/mp4"):
        source=audiostream,
        sourceaudiotype="audio/mp3"):

    #define button order
    if button == 0: fbuttons = [0, 1, 2]
    if button == 1: fbuttons = [1, 0, 2]
    if button == 2: fbuttons = [2, 0, 1]
    newbutton = button

    #Illuminate status indicator
    GPIO.output(lights[button], True)
    print("Attempting Cast...")

    #Open connection to chromecast device
    chromecasts, browser = pychromecast.get_listed_chromecasts(
        friendly_names=[targets[button]])
    cast = chromecasts[0]

    #start worker thread and wait for cast device to be ready
    cast.wait()
    print("Casting to " + cast.device.friendly_name)

    #start media
    mc = cast.media_controller
    cast.set_volume(initialVolume / 100)
    mc.play_media(source, sourceaudiotype)
    mc.block_until_active()
    print(mc.status.player_state)

    #wait for stream start
    time.sleep(5)
    timeout = 5
    while mc.status.player_state != "PLAYING" and timeout < connectiontimeout:
        time.sleep(1)
        timeout = timeout + 1
        print(timeout)
    print(mc.status.player_state)

    #start PWM and volume control
    setVolumeCounter = 1
    priorVolume = initialVolume
    counter = initialVolume
    clkLastState = GPIO.input(clk)
    pwm.ChangeDutyCycle(counter * VoltMeterScale)

    #Loop to control volume and monitor for button presses
    while (mc.status.player_state == "PLAYING"
           or mc.status.player_state == "BUFFERING"):
        #while GPIO.input(button)==True:
        clkState = GPIO.input(clk)
        dtState = GPIO.input(dt)
        if clkState != clkLastState:
            if dtState == clkState and counter < 100:
                counter += increment
            elif counter > 0:
                counter -= increment
            #print(counter)
            pwm.ChangeDutyCycle(counter * VoltMeterScale)
        setVolumeCounter = (setVolumeCounter + 1) % setVolumeInterval
        if setVolumeCounter == 0 and priorVolume != counter:
            #print("Set Volume")
            cast.set_volume(counter / 100)
            priorVolume = counter
        clkLastState = clkState
        if (GPIO.input(buttons[0]) == False or GPIO.input(buttons[1]) == False
                or GPIO.input(buttons[2]) == False):
            if GPIO.input(buttons[fbuttons[1]]) == False:
                newbutton = fbuttons[1]
            if GPIO.input(buttons[fbuttons[2]]) == False:
                newbutton = fbuttons[2]
            break
        time.sleep(.002)
        #print(mc.status.player_state)
        #print(GPIO.input(button))

    #End cast, close connection, and turn off light and volume
    print("Closing Cast Session")
    GPIO.output(lights[button], False)
    pwm.ChangeDutyCycle(0)
    mc.stop()
    time.sleep(1)
    #print(mc.status.player_state)
    #cast.disconnect()
    pychromecast.discovery.stop_discovery(browser)
    time.sleep(1)

    print(button)
    print(newbutton)
    if newbutton == button: return

    print("didn't leave")
    cast_and_monitor(newbutton)
Exemplo n.º 12
0
    podcast_data = json.load(json_file)

if len(podcast_data) == 0:
    getUpdate()
    with open('podcasts.json') as json_file:
        podcast_data = json.load(json_file)

podcasts_to_play = []

logging.info(f'Going to play: {total_podcast_to_play}')
logging.info(f'Chromecast: {chromecast_name}')

logging.info("Selecting Podcasts")

count = 0

while len(podcasts_to_play) < total_podcast_to_play:
    podCast_selected = random.choice(podcast_data)
    podcasts_to_play.append(podCast_selected)
    podcast_title = podCast_selected['title']
    logging.info(f'{count} : {podcast_title}')
    count = count + 1

ChromeCasts, browser = pychromecast.get_listed_chromecasts(
    friendly_names=[chromecast_name])

ChromeCast = next(ChromeCast for ChromeCast in ChromeCasts)
ChromeCast.wait()

p = Player(ChromeCast)
p.play(podcasts_to_play)
Exemplo n.º 13
0
def run_spotify():
    """
	Example on how to use the Spotify Controller.
	NOTE: You need to install the spotipy and spotify-token dependencies.
	
	This can be done by running the following:
	pip install spotify-token
	pip install git+https://github.com/plamere/spotipy.git
	"""
    import argparse
    import logging
    import time
    import sys

    import pychromecast
    from pychromecast.controllers.spotify import SpotifyController
    import spotify_token as st
    import spotipy

    CAST_NAME = "My Chromecast"

    parser = argparse.ArgumentParser(
        description="Example on how to use the Spotify Controller.")
    parser.add_argument("--show-debug",
                        help="Enable debug log",
                        action="store_true")
    parser.add_argument("--cast",
                        help='Name of cast device (default: "%(default)s")',
                        default=CAST_NAME)
    parser.add_argument("--user", help="Spotify username", required=True)
    parser.add_argument("--password", help="Spotify password", required=True)
    parser.add_argument(
        "--uri",
        help='Spotify uri(s) (default: "%(default)s")',
        default=["spotify:track:3Zwu2K0Qa5sT6teCCHPShP"],
        nargs="+",
    )
    args = parser.parse_args()

    if args.show_debug:
        logging.basicConfig(level=logging.DEBUG)
        # Uncomment to enable http.client debug log
        # http_client.HTTPConnection.debuglevel = 1

    chromecasts = pychromecast.get_listed_chromecasts(
        friendly_names=[args.cast])
    cast = None
    for _cast in chromecasts:
        if _cast.name == args.cast:
            cast = _cast
            break

    if not cast:
        print('No chromecast with name "{}" discovered'.format(args.cast))
        print("Discovered casts: {}".format(chromecasts))
        sys.exit(1)

    print("cast {}".format(cast))

    class ConnListener:
        def __init__(self, mz):
            self._mz = mz

        def new_connection_status(self, connection_status):
            """Handle reception of a new ConnectionStatus."""
            if connection_status.status == "CONNECTED":
                self._mz.update_members()

    class MzListener:
        def __init__(self):
            self.got_members = False

        def multizone_member_added(self, uuid):
            pass

        def multizone_member_removed(self, uuid):
            pass

        def multizone_status_received(self):
            self.got_members = True

    # Wait for connection to the chromecast
    cast.wait()

    spotify_device_id = None

    # Create a spotify token
    data = st.start_session(args.user, args.password)
    access_token = data[0]
    expires = data[1] - int(time.time())

    # Create a spotify client
    client = spotipy.Spotify(auth=access_token)
    if args.show_debug:
        spotipy.trace = True
        spotipy.trace_out = True

    # Launch the spotify app on the cast we want to cast to
    sp = SpotifyController(access_token, expires)
    cast.register_handler(sp)
    sp.launch_app()

    if not sp.is_launched and not sp.credential_error:
        print("Failed to launch spotify controller due to timeout")
        sys.exit(1)
    if not sp.is_launched and sp.credential_error:
        print("Failed to launch spotify controller due to credential error")
        sys.exit(1)

    # Query spotify for active devices
    devices_available = client.devices()

    # Match active spotify devices with the spotify controller's device id
    for device in devices_available["devices"]:
        if device["id"] == sp.device:
            spotify_device_id = device["id"]
            break

    if not spotify_device_id:
        print('No device with id "{}" known by Spotify'.format(sp.device))
        print("Known devices: {}".format(devices_available["devices"]))
        sys.exit(1)

    # Start playback
    if args.uri[0].find("track") > 0:
        client.start_playback(device_id=spotify_device_id, uris=args.uri)
    else:
        client.start_playback(device_id=spotify_device_id,
                              context_uri=args.uri[0])
Exemplo n.º 14
0
                print(response.headers['Content-Type'])
                return response.headers['Content-Type']
            else:
                raise Exception("Bad status {}".format(response.status))


loop = asyncio.get_event_loop()
fmt = loop.run_until_complete(main(url))

print(fmt)

pychromecast.IGNORE_CEC.append(
    target_device)  # Ignore CEC on Chromecasts named Living Room

services, browser = pychromecast.discovery.discover_chromecasts()
chromecasts, browser = pychromecast.get_listed_chromecasts(
    friendly_names=[target_device])

print(chromecasts)
cast = chromecasts[0] if len(chromecasts) == 1 else next(
    cc for cc in chromecasts if cc.device.friendly_name == target_device)

cast.wait()
print(cast.device)
print(cast.status)

mc = cast.media_controller

mc.play_media(url, fmt)

print(mc.status)
mc.block_until_active()
Exemplo n.º 15
0
import time
import pychromecast
services, browser = pychromecast.discovery.discover_chromecasts()
pychromecast.discovery.stop_discovery(browser)
for cast in services:
    print(cast[2], ":", cast[3], ":", cast[4])
    chromecasts, browser = pychromecast.get_listed_chromecasts(
        friendly_names=[cast[3]])
    [cc.device.friendly_name for cc in chromecasts]
cast = chromecasts[0]
cast.wait()
print(cast.device)
print(cast.status)

mc = cast.media_controller
mc.play_media('http://kristofer.is/meme/spooky.mp3', 'audio/mp3')
mc.block_until_active()
print(mc.status)
pychromecast.discovery.stop_discovery(browser)
Exemplo n.º 16
0
def launch_spotify(target, user, password, uri):

    chromecasts = pychromecast.get_listed_chromecasts(friendly_names=target)
    cast = None
    for _cast in chromecasts:
        if _cast.name == target:
            cast = _cast
            break

    if not cast:
        print('No chromecast with name "{}" discovered'.format(target))
        print("Discovered casts: {}".format(chromecasts))
        sys.exit(1)

    print("cast {}".format(cast))

    class ConnListener:
        def __init__(self, mz):
            self._mz = mz

        def new_connection_status(self, connection_status):
            """Handle reception of a new ConnectionStatus."""
            if connection_status.status == "CONNECTED":
                self._mz.update_members()

    class MzListener:
        def __init__(self):
            self.got_members = False

        def multizone_member_added(self, uuid):
            pass

        def multizone_member_removed(self, uuid):
            pass

        def multizone_status_received(self):
            self.got_members = True

    # Wait for connection to the chromecast
    cast.wait()

    spotify_device_id = None

    # Create a spotify token
    data = st.start_session(user, password)
    access_token = data[0]
    expires = data[1] - int(time.time())

    #Create spotify client
    client = spotipy.Spotify(auth=access_token)

    # Launch the spotify app on cast device
    sp = SpotifyController(access_token, expires)
    cast.register_handler(sp)
    sp.launch_app()

    if not sp.is_launched and not sp.credential_error:
        print("Failed to launch spotify controller due to timeout")
        sys.exit(1)
    if not sp.is_launched and sp.credential_error:
        print("Failed to launch spotify controller due to credential error")
        sys.exit(1)

    # Query spotify for active devices
    devices_available = client.devices()

    # Match active spotify devices with the spotify controller's device id
    for device in devices_available["devices"]:
        if device["id"] == sp.device:
            spotify_device_id = device["id"]
            break

    if not spotify_device_id:
        print('No device with id "{}" known by Spotify'.format(sp.device))
        print("Known devices: {}".format(devices_available["devices"]))
        sys.exit(1)

    # Start playback
    client.start_playback(device_id=spotify_device_id, context_uri=uri)
Exemplo n.º 17
0
import time
import os
import pychromecast
import pychromecast.controllers.dashcast as dashcast

DASHBOARD_URL = os.getenv('DASHBOARD_URL')
DISPLAY_NAME = os.getenv('DISPLAY_NAME')

print('List chromecasts on the network, but don\'t connect')
services, browser = pychromecast.discovery.discover_chromecasts()

print('Discover and connect to chromecasts named:', DISPLAY_NAME)
chromecasts, browser = pychromecast.get_listed_chromecasts(
    friendly_names=[DISPLAY_NAME])
[cc.device.friendly_name for cc in chromecasts]
print('Found:', chromecasts)
cast = chromecasts[0]
print('Selected:', cast)

print('Start worker thread and wait for cast device to be ready')
cast.wait()
controller = dashcast.DashCastController()
cast.register_handler(controller)
print()
time.sleep(1)
print(cast.device.friendly_name, ':', cast.status.status_text)
print()
print(cast.media_controller.status)
print()

if not cast.is_idle:
Exemplo n.º 18
0
	if sys.argv[1]=="--d":
		print(" \33[92m",len(services),"\33[0m Devices found")
		print("\t Name\t UID")
		for x in  range(len(services)):
			print("\33[94m %d. \33[0m\t %s\t %s"% (x,services[x][3],services[x][1]))



else:
	print("\33[92m",len(services),"\33[0m Devices found")
	print("\t Name\t UID")
	for x in  range(len(services)):
		print("\33[94m %d. \33[0m \t%s\t "% (x,services[x][3]))
print('Enter number of device: ',end='')

chromecasts, browser = pychromecast.get_listed_chromecasts(friendly_names=[services[int(input())][3]])
[cc.device.friendly_name for cc in chromecasts]
cast = chromecasts[0]
if len(cast.device)==5:
	print("Connected")
else:
	print("Connection error")
	print(cast.device)
	print(cast.status)
	exit()
cast.wait()
#print(cast.device)
#print(cast.status)
mc = cast.media_controller
mc.block_until_active()
Exemplo n.º 19
0
#!/usr/bin/env python
# In progress:
# Python script to Chromecast Twitch.tv

import time
import pychromecast

# Run in Python interpreter to list chromecasts on the network, but don't connect
# services, browser = pychromecast.discovery.discover_chromecasts()
# Shut down discovery
# pychromecast.discovery.stop_discovery(browser)

# Discover and connect to chromecasts named Living Room
chromecasts, browser = pychromecast.get_listed_chromecasts(
    friendly_names=["Living Room TV"])
[cc.device.friendly_name for cc in chromecasts]
#['Living Room TV']

cast = chromecasts[0]
# Start worker thread and wait for cast device to be ready
cast.wait()
#print(cast.device)
#DeviceStatus(friendly_name='Living Room TV', model_name='Chromecast', manufacturer='Google Inc.', uuid=UUID('a8ca9b5e-0d6b-e5c8-1924-5015c213a5d0'), cast_type='cast')

#print(cast.status)
#CastStatus(is_active_input=True, is_stand_by=False, volume_level=1.0, volume_muted=False, app_id='CC1AD845', display_name='Default Media Receiver', namespaces=['urn:x-cast:com.google.cast.player.message', 'urn:x-cast:com.google.cast.media'], session_id='CCA39713-9A4F-34A6-A8BF-5D97BE7ECA5C', transport_id='web-9', status_text='')

mc = cast.media_controller
mc.play_media('https://www.twitch.tv/cohhcarnage', 'video/mp4')
#mc.play_media('http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4', 'video/mp4')
mc.block_until_active()
Exemplo n.º 20
0
    sys.exit(1)

logger = logging.getLogger("chromecast_monitor")
log_level = logging.DEBUG if args.show_debug else logging.INFO
stream_handler = logging.StreamHandler()
# stream_handler.setLevel(log_level)
file_handler = logging.FileHandler(args.file)
# file_handler.setLevel(log_level)
logging.basicConfig(level=log_level,
                    format=FORMAT,
                    handlers=[stream_handler, file_handler])
if args.show_zeroconf_debug:
    logger.debug("Zeroconf version: " + zeroconf.__version__)
    logging.getLogger("zeroconf").setLevel(logging.DEBUG)

chromecasts, browser = pychromecast.get_listed_chromecasts(
    friendly_names=args.chromecasts)
if not chromecasts:
    logger.fatal('No chromecast with name "{}" discovered'.format(args.cast))
    sys.exit(1)

for chromecast in chromecasts:
    # Start socket client's worker thread and wait for initial status update
    chromecast.wait()

    listenerCast = StatusListener(chromecast.name, chromecast)
    chromecast.register_status_listener(listenerCast)

    listenerMedia = StatusMediaListener(chromecast.name, chromecast)
    chromecast.media_controller.register_status_listener(listenerMedia)

input("Listening for Chromecast events...\n\n")
Exemplo n.º 21
0
    language_chooser = TranslationChooser("fin")
    httpclient = HttpClient(None)
    stream_filters = StreamFilters()

    url = "https://areena.yle.fi/{}".format(program_id)

    extractor = extractor_factory(url, stream_filters, language_chooser, httpclient)
    pid = extractor.program_id_from_url(url)

    info = extractor.program_info_for_pid(pid, url, title_formatter, None)

    return info.media_id.split("-")[-1]


chromecasts, browser = pychromecast.get_listed_chromecasts(
    friendly_names=[args.cast], known_hosts=args.known_host
)
if not chromecasts:
    print('No chromecast with name "{}" discovered'.format(args.cast))
    sys.exit(1)

cast = chromecasts[0]
# Start socket client's worker thread and wait for initial status update
cast.wait()

yt = YleAreenaController()
cast.register_handler(yt)
yt.play_areena_media(
    get_kaltura_id(args.program),
    audio_language=args.audio_language,
    text_language=args.text_language,
    def run(self):
        try:
            print('Server started at %s:%s!' % (local_ip, self.server_address[1]))
            self.serve_forever()
        except KeyboardInterrupt:
            pass
        finally:
            self.server_close()

# start server in background
server = StoppableHTTPServer(('', PORT), http.server.SimpleHTTPRequestHandler)
thread = threading.Thread(None, server.run)
thread.start()

# connect to Google Nest Hub
chromecasts, browser = pychromecast.get_listed_chromecasts(friendly_names=["Office"])
ghome = chromecasts[0]
ghome.wait()

os.makedirs('cache', exist_ok=True)
fname = 'cache/cache.mp3'

mc = ghome.media_controller
def speechtospeaker(say, langu):
    global local_ip
    global PORT
    global fname
    global mc
    
    tts = gTTS(say, lang=langu)
    tts.save(fname)
Exemplo n.º 23
0
    "--show-status-only", help="Show status, then exit", action="store_true"
)
parser.add_argument(
    "--cast", help='Name of cast device (default: "%(default)s")', default=CAST_NAME
)
parser.add_argument(
    "--url", help='Media url (default: "%(default)s")', default=MEDIA_URL
)
args = parser.parse_args()

if args.show_debug:
    fmt = "%(asctime)s %(levelname)s (%(threadName)s) [%(name)s] %(message)s"
    datefmt = "%Y-%m-%d %H:%M:%S"
    logging.basicConfig(format=fmt, datefmt=datefmt, level=logging.DEBUG)

chromecasts = pychromecast.get_listed_chromecasts(friendly_names=[args.cast])
if not chromecasts:
    print('No chromecast with name "{}" discovered'.format(args.cast))
    sys.exit(1)

cast = chromecasts[0]

# Start socket client's worker thread and wait for initial status update
cast.wait()

print()
print(cast.device)
time.sleep(1)
print()
print(cast.status)
print()
Exemplo n.º 24
0
import time
import pychromecast
castNames = []
services, browser = pychromecast.discovery.discover_chromecasts()
pychromecast.discovery.stop_discovery(browser)
for cast in services:
    print(cast[2], ":", cast[3], ":", cast[4])
    castNames.append(cast[3])

for thing in castNames:
    chromecasts, browser = pychromecast.get_listed_chromecasts(
        friendly_names=[thing])
    [cc.device.friendly_name for cc in chromecasts]
    cast = chromecasts[0]
    cast.wait()
    print(cast.device)
    print(cast.status)
    mc = cast.media_controller
    #mc.play_media('http://kristofer.is/meme/spooky.mp3', 'audio/mp3')
    #mc.block_until_active()

    print(mc.status)
    pychromecast.discovery.stop_discovery(browser)
    print("----------------------------------------------")