home-assistant-libs / pychromecast

Library for Python 3 to communicate with the Google Chromecast.
MIT License
2.53k stars 377 forks source link

Correct way to launch URL? #148

Open smblott-github opened 7 years ago

smblott-github commented 7 years ago

Here's a simplified version of my script...

import socket, pychromecast, time

address = socket.gethostbyname("chromecast-kitchen")
sundtek_url = "http://192.168.3.2:8088/sundtek.mp3"
sundtek_mime = "audio/mp3"

cast = pychromecast.Chromecast(address)
controller = cast.media_controller
cast.wait()

controller.play_media(sundtek_url, sundtek_mime, stream_type="LIVE")
time.sleep(2) # Why is this needed?  What is the correct way of doing this?

cast.disconnect(None, False)

The problem is the time.sleep(). Without this, the URL does not launch.

What is the correct way to wait for the .play_media() to have completed?

(Possibly related to #128.)

piedar commented 7 years ago

It used to work like this:

while not controller.status.player_is_idle:
    time.sleep(1)

But that doesn't seem reliable any more, so try callbacks instead.

completion = threading.Event()
class status_listener:
    def new_media_status(status):
        if status.player_is_idle:
            completion.set()

controller.register_status_listener(status_listener())
controller.play_media(url, filetype)

# poll so signal handlers still work
while not completion.wait(0.5):
    pass
OttoWinter commented 6 years ago

You could also try MediaController.block_until_active like this:

import pychromecast

c = pychromecast.Chromecast(address)
mc = cast.media_controller
c.wait()

mc.play_media(sundtek_url, sundtek_mime, stream_type="LIVE")
mc.block_until_active()