Example #1
0
def playYoutubeVideo(request, cast_name, video_id):
    yt = YouTubeController()
    cast = pycc.get_chromecast(friendly_name=cast_name)

    cast.register_handler(yt)
    yt.play_video(video_id)
    return HttpResponse("Playing {} on {}".format(video_id, cast_name))
Example #2
0
class myChromeCast:
    
    #Leapcast?

    def __init__(self):
        
        self.ChromeCastName = "FILL"
        self.cast = pychromecast.get_chromecast(friendly_name=self.ChromeCastName)
    
        self.mc = self.cast.media_controller

    def playVideo(self, youtubeLink):
        
        self.quitApp()
        
        self.yt = YouTubeController()
        
        self.cast.register_handler(self.yt)
    
        self.yt.play_video(youtubeLink)

    def play(self):
    
        self.mc.play()

    def pause(self):

        self.mc.pause()

    def quitApp(self):

        self.cast.quit_app()
Example #3
0
 def playVideo(self, youtubeLink):
     
     self.quitApp()
     
     self.yt = YouTubeController()
     
     self.cast.register_handler(self.yt)
 
     self.yt.play_video(youtubeLink)
Example #4
0
 def __init__(self, device: Chromecast, status: ChromeState):
     self.chromestate = status
     self.device = device
     self.log = logging.getLogger('Command_' + self.device.name)
     self.youtube = YouTubeController()
     self.device.register_handler(self.youtube)
Example #5
0
class Command:
    '''
    Class that handles dispatching of commands to a chromecast device
    '''
    def __init__(self, device: Chromecast, status: ChromeState):
        self.chromestate = status
        self.device = device
        self.log = logging.getLogger('Command_' + self.device.name)
        self.youtube = YouTubeController()
        self.device.register_handler(self.youtube)

    def execute(self, cmd, payload):
        '''execute command on the chromecast

        Arguments:
            cmd {[string]}
            payload {[string]}

        Returns:
            Result -- result object from the command execution
        '''
        method = getattr(self, cmd, lambda x: False)
        sig = signature(method)
        if str(sig) == '(x)':
            return False

        if len(sig.parameters) == 0:  #pylint: disable=len-as-condition
            method()
        else:
            method(payload)
        return True

    def stop(self):
        ''' Stop playing on the chromecast '''
        self.device.media_controller.stop()

    def pause(self, pause):
        ''' Pause playback '''
        if (pause is None or pause == ''):
            if self.device.media_controller.is_paused:
                self.device.media_controller.play()
            else:
                self.device.media_controller.pause()
        else:
            pause = str(pause).lower()
            if pause in ('1', 'true'):
                self.device.media_controller.pause()
            elif pause in ('0', 'false'):
                self.device.media_controller.play()
            else:
                raise CommandException(
                    'Pause could not match "{0}" as a parameter'.format(pause))

    def fwd(self):
        ''' Skip to next track '''
        self.log.warning('fwd is a deprecated function, use next instead')
        return self.next()

    def rev(self):
        ''' Rewind to previous track '''
        self.log.warning('rev is a deprecated function, use prev instead')
        return self.prev()

    def next(self):
        ''' Skip to next track '''
        self.device.media_controller.queue_next()

    def prev(self):
        ''' Rewind to previous track '''
        self.device.media_controller.queue_prev()

    def quit(self):
        ''' Quit running application on chromecast '''
        self.chromestate.clear()
        self.device.quit_app()

    def play(self, media=None):
        ''' Play a media URL on the chromecast '''
        if media is None or media == '':
            self.device.media_controller.play()
        else:
            self.__play_content(media)

    def __play_content(self, media):
        media_obj = "Failed"

        try:
            media_obj = json.loads(media, object_hook=lambda d: Namespace(**d))
        except:
            raise CommandException(
                "{0} is not a valid json object".format(media))

        if not hasattr(media_obj, 'link') or not hasattr(media_obj, 'type'):
            raise CommandException(
                'Wrong parameter, it should be json object with: {{link: string, type: string}}, you sent {0}'
                .format(media)  #pylint: disable=line-too-long
            )

        retry = 3
        media_type = media_obj.type.lower()
        while True:
            if media_type == 'youtube':
                self.youtube.play_video(media_obj.link)
            else:
                self.device.media_controller.play_media(
                    media_obj.link, media_obj.type)
            sleep(0.5)
            if self.device.media_controller.is_playing or retry == 0:
                break
            retry = retry - 1

    def volume(self, level):
        ''' Set the volume level '''
        if level is None or level == '':
            raise CommandException('You need to specify volume level')
        if int(level) > 100:
            level = 100
        if int(level) < 0:
            level = 0
        self.device.set_volume(int(level) / 100.0)

    def mute(self, mute):
        ''' Mute device '''
        if (mute is None or mute == ''):
            self.device.set_volume_muted(not self.device.status.volume_muted)
        else:
            mute = str(mute).lower()
            if mute in ('1', 'true'):
                self.device.set_volume_muted(True)
            elif mute in ('0', 'false'):
                self.device.set_volume_muted(False)
            else:
                raise CommandException(
                    'Mute could not match "{0}" as a parameter'.format(mute))

    def update(self):
        ''' Request an update from the chromecast '''
        self.device.media_controller.update_status()
Example #6
0
import time
import pychromecast
from pychromecast.controllers.youtube import YouTubeController

chromecasts = pychromecast.get_chromecasts()
x = [cc.device.friendly_name for cc in chromecasts]
VIDEO_ID = "0jm8nnHqx80"
print(x)

cast = next(cc for cc in chromecasts
            if cc.device.friendly_name == "Beat Chromecast")
#  # Start worker thread and wait for cast device to be ready
cast.wait()
print(cast.device)
# DeviceStatus(friendly_name='Living Room', model_name='Chromecast', manufacturer='Google Inc.', uuid=UUID('df6944da-f016-4cb8-97d0-3da2ccaa380b'), 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='')
yt = YouTubeController()
cast.register_handler(yt)
yt.play_video(VIDEO_ID)

# mc = cast.media_controller
# mc.play_media('http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4', 'video/mp4')
# mc.block_until_active()
# print(mc.status)
# MediaStatus(current_time=42.458322, content_id='http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4', content_type='video/mp4', duration=596.474195, stream_type='BUFFERED', idle_reason=None, media_session_id=1, playback_rate=1, player_state='PLAYING', supported_media_commands=15, volume_level=1, volume_muted=False)

#  mc.pause()
#  time.sleep(5)
#  mc.play(
Example #7
0
 def __init__(self, cast, app, prep=None):
     self._controller = YouTubeController()
     super(YoutubeCastController, self).__init__(cast, app, prep=prep)
     self.info_type = "id"
     self.save_capability = "partial"
     self.playlist_capability = "complete"
 def receive_message(self, msg, data):
     logger.debug('Received: %s %s' % (msg, data))
     return YouTubeController.receive_message(self, msg, data)
Example #9
0
class ChromecastWrapper(Wrapper):
  """
  A wrapper to make it easier to switch out backend implementations.

  Holds common logic for dealing with underlying Chromecast API.
  """

  def __init__(self, cc: Chromecast):
    self.cc = cc
    self.yt_ctl = YouTubeController()
    self.cc.register_handler(self.yt_ctl)

  def __getattr__(self, name: str) -> Any:
    return getattr(self.cc, name)

  def __repr__(self) -> str:
    return f"<{self.__name__} for {self.cc}>"

  @property
  def cast_status(self) -> Union[CastStatus, ReturnsNone]:
    if self.cc.status:
      return self.cc.status

    return ReturnsNone()

  @property
  def media_status(self) -> Union[MediaStatus, ReturnsNone]:
    if self.cc.media_controller.status:
      return self.cc.media_controller.status

    return ReturnsNone()

  def can_play_next(self) -> Optional[bool]:
    if self.media_status:
      return self.media_status.supports_queue_next

    return False

  def can_play_prev(self) -> Optional[bool]:
    if self.media_status:
      return self.media_status.supports_queue_prev

    return False

  def play_next(self):
    self.cc.media_controller.queue_next()

  def play_prev(self):
    self.cc.media_controller.queue_prev()

  def can_pause(self) -> Optional[bool]:
    return self.media_status.supports_pause

  def can_seek(self) -> Optional[bool]:
    return self.media_status.supports_seek

  def quit(self):
    self.cc.quit_app()

  def get_current_position(self) -> Microseconds:
    position_secs = self.media_status.adjusted_current_time

    if position_secs:
      return int(position_secs * US_IN_SEC)

    return BEGINNING

  def next(self):
    self.cc.play_next()

  def previous(self):
    self.cc.play_previous()

  def pause(self):
    self.cc.media_controller.pause()

  def resume(self):
    self.play()

  def stop(self):
    self.cc.media_controller.stop()

  def play(self):
    self.cc.media_controller.play()

  def get_playstate(self) -> PlayState:
    if self.cc.media_controller.is_paused:
      return PlayState.PAUSED

    elif self.cc.media_controller.is_playing:
      return PlayState.PLAYING

    return PlayState.STOPPED

  def seek(self, time: Microseconds):
    seconds = int(round(time / US_IN_SEC))
    self.cc.media_controller.seek(seconds)

  def open_uri(self, uri: str):
    video_id = get_video_id(uri)

    if video_id:
      self.play_youtube(video_id)
      return

    mimetype, _ = guess_type(uri)
    self.cc.media_controller.play_media(uri, mimetype)

  def is_repeating(self) -> bool:
    return False

  def is_playlist(self) -> bool:
    return self.can_go_next() or self.can_go_previous()

  def set_repeating(self, val: bool):
    pass

  def set_loop_status(self, val: str):
    pass

  def get_rate(self) -> RateDecimal:
    return DEFAULT_RATE

  def set_rate(self, val: RateDecimal):
    pass

  def get_shuffle(self) -> bool:
    return False

  def set_shuffle(self, val: bool):
    return False

  def get_art_url(self, track: int = None) -> str:
    thumb = self.media_controller.thumbnail
    return thumb if thumb else DEFAULT_THUMB

  def get_volume(self) -> VolumeDecimal:
    return self.cast_status.volume_level

  def set_volume(self, val: VolumeDecimal):
    curr = self.get_volume()
    diff = val - curr

    # can't adjust vol by 0
    if diff > NO_DELTA:  # vol up
      self.cc.volume_up(diff)

    elif diff < NO_DELTA:
      self.cc.volume_down(abs(diff))

  def is_mute(self) -> Optional[bool]:
    if self.cast_status:
      return self.cast_status.volume_muted

    return False

  def set_mute(self, val: bool):
    self.cc.set_volume_muted(val)

  def get_stream_title(self) -> str:
    title = self.cc.media_controller.title
    metadata = self.media_status.media_metadata

    if metadata and 'subtitle' in metadata:
      title = ' - '.join((title, metadata['subtitle']))

    return title

  def get_duration(self) -> Microseconds:
    duration = self.media_status.duration

    if duration:
      duration *= US_IN_SEC

    else:
      duration = NO_DURATION

    return duration

  def metadata(self) -> Metadata:
    title: str = self.get_stream_title()
    dbus_name: DbusObj = get_track_id(title)

    artist: Optional[str] = self.media_status.artist
    artists: List[str] = [artist] if artist else []
    comments: List[str] = []

    metadata = {
      "mpris:trackid": dbus_name,
      "mpris:length": self.get_duration(),
      "mpris:artUrl": self.get_art_url(),
      "xesam:url": self.media_status.content_id,
      "xesam:title": title,
      "xesam:artist": artists,
      "xesam:album": self.media_status.album_name,
      "xesam:albumArtist": artists,
      "xesam:discNumber": DEFAULT_DISC_NO,
      "xesam:trackNumber": self.media_status.track,
      "xesam:comment": comments,
    }

    return metadata

  def get_current_track(self) -> Track:
    art_url = self.get_art_url()
    content_id = self.media_status.content_id
    name = self.media_status.artist
    duration = int(self._get_duration())
    title = self.get_stream_title()
    artist = Artist(name)

    album = Album(
      name=self.media_status.album_name,
      artists=(artist,),
      art_url=art_url,
    )

    track = Track(
      track_id=get_track_id(title),
      name=title,
      track_no=self.media_status.track,
      length=duration,
      uri=content_id,
      artists=(artist,),
      album=album,
      art_url=art_url,
      disc_no=DEFAULT_DISC_NO,
      type=get_media_type(self.cc)
    )

    return track

  def get_desktop_entry(self) -> str:
    return str(Path(DESKTOP_FILE).absolute())

  def launch_youtube(self):
    self.yt_ctl.launch()

  def play_youtube(self, video_id: str):
    if not self.yt_ctl.is_active:
      self.launch_youtube()

    self.yt_ctl.play_video(video_id)

  def add_track(
    self,
    uri: str,
    after_track: DbusObj,
    set_as_current: bool
  ):
    video_id = get_video_id(uri)

    if video_id:
      self.yt_ctl.add_to_queue()
Example #10
0
class castDevice:

    def __init__(self):
        self.available_devices = None
        self.chosen_device = None
        self.cast = None
        self.cast_media = None
        self.video = None
        self.youtube_controler = YouTubeController()
        self.ydl_opts = {
            'noplaylist': True,
            'playlistend': 1
        }

    def find_devices(self):
        self.available_devices = pychromecast.get_chromecasts()

    def get_device_list_names(self):
        names = []

        for cc in self.available_devices:
            names.append(cc.device.friendly_name)

        return names

    def choose_casting_device(self):
        self.cast = next(cc for cc in self.available_devices if cc.device.friendly_name == self.chosen_device)
        self.cast.wait()
        self.cast_media = self.cast.media_controller
        self.cast.register_handler(self.youtube_controler)
        print(self.cast.device)

    def translate_from_youtube(self, search_query):
        search = list(search_query)
        for i in range(len(search)):
            if search[i] == ' ':
                search[i] = '+'

        search = "".join(search)
        target_url = "https://www.youtube.com/results?search_query={}&page=1".format(search)

        with youtube_dl.YoutubeDL(self.ydl_opts) as ydownloader:
            ytdata = ydownloader.extract_info(target_url, download=False)
            self.video=convert_to_list(ytdata['entries'])[0]['id']
            print(self.video)

    def play_on_youtube(self,string):
        self.translate_from_youtube(string)
        self.youtube_controler.play_video(self.video)

    def add_to_playlist(self,string):
        self.translate_from_youtube(string)
        self.youtube_controler.play_next(self.video)

    def simple_play(self, video_link):
        self.cast_media.play_media(video_link, 'video/mp4')

    def stop_casting(self):
        self.cast_media.stop()

    def pause(self):
        self.cast_media.pause()

    def resume(self):
        self.cast_media.play()
Example #11
0
def main():

    os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'

    PLAYLIST = {}

    # Authenticate OAuth2 with Google
    creds = client.GoogleCredentials(access_token=None,
                                     client_id=CLIENT_ID,
                                     client_secret=CLIENT_SECRET,
                                     refresh_token=REFRESH_TOKEN,
                                     token_expiry=None,
                                     token_uri=TOKEN_URI,
                                     user_agent=USER_AGENT)

    http = creds.authorize(httplib2.Http())
    creds.refresh(http)

    # Build the service
    youtube = build(API_SERVICE_NAME, API_VERSION, http=http)

    # Randomize Playlists
    # Comment this line if you don't want randomized playlists
    random.shuffle(SERIAL_LIST)

    # Loop through each playlist
    for serials in SERIAL_LIST:

        # Retrieve video's JSON values
        request = youtube.playlistItems().list(part="snippet,contentDetails",
                                               maxResults=10,
                                               playlistId=serials)

        response = request.execute()

        # Get a list of playlist items
        list_of_videos = response.get('items')
        video_ids = []

        # For each playlist item, get the corresponding video id
        for vids in list_of_videos:
            content_details = vids.get('contentDetails')
            snippet = vids.get('snippet')
            # Region blocking, age-restriction, deleted vid - maybe, later ....

            # Check if video is private
            if snippet.get('title') != "Private video":
                video_ids.append(content_details.get('videoId'))

        PLAYLIST[serials] = video_ids

    # Combine all video id's together into Queue
    # Plays the videos in playlist in order
    x = PLAYLIST.values()
    queue = [j for i in x for j in i][::-1]

    # If you want to randomize the videos, uncomment below
    # random.shuffle(queue)

    cast = None

    # Keep trying to connect until wanted chromecast is online
    while (cast == None):
        chromecasts, browsers = pychromecast.get_chromecasts()
        try:
            # Loop through all the chromecasts in the house
            cast = next(cc for cc in chromecasts
                        if cc.device.friendly_name == CAST_NAME)
        except:
            print("Chromecast Not Found")

    cast.wait()

    # Create Youtube Controller + Register it
    yt = YouTubeController()
    cast.register_handler(yt)

    # Create a new Youtube Session
    yt.start_session_if_none()
    s1 = yt._session
    s1._start_session()

    # Initialize the Queue to play
    s1._initialize_queue(queue[0])

    print("Queue Play Order: ")
    print("1. " + queue[0])
    order = 2

    # Add wanted video id's to the Queue
    for id in queue[1:]:
        print(str(order) + ". " + id)
        yt.add_to_queue(id)
        order += 1
Example #12
0
 def cast_youtube(self, video_id):
     if self.yt is None:
         yt = YouTubeController()
         self.cast_.register_handler(yt)
     yt.play_video(video_id)
     return True
Example #13
0
import pychromecast
from pychromecast.controllers.youtube import YouTubeController

CAST_NAME = "Xbox_One"

chromecasts = pychromecast.get_chromecasts()
if len(chromecasts) == 0:
    print("NO CHROMO")
else:
    cast = next(cc for cc in chromecasts
                if cc.device.friendly_name == CAST_NAME)
    cast.wait()
    yt = YouTubeController()
    cast.register_handler(yt)
Example #14
0
def main() :

    cast =  init()
    yt = YouTubeController()
    cast.register_handler(yt)
    yt.play_video('wDgQdr8ZkTw')
#!/usr/bin/python3

import pychromecast as c
from pychromecast.controllers.youtube import YouTubeController

chromecast = c.Chromecast('212.10.46.242')

chromecast.wait()

print(chromecast.device.friendly_name)
print(chromecast.status.display_name)

yt = YouTubeController()
chromecast.register_handler(yt)

yt.play_video("tD8GLL1jz94")
#yt.play_video("19ro0Giif34", "RDtpt56VsvbJg")
#yt.play_next("7Zx_xAC1sxA")

print(chromecast.status.display_name)

import re, requests, json
from config import *

#initialize chromecast
if chromeCast:
    import pychromecast
    from pychromecast.controllers.youtube import YouTubeController
    chromecasts = pychromecast.get_chromecasts()
    try:
        cast = next(cc for cc in chromecasts
                    if cc.device.friendly_name == chromeCastName)
        cast.wait()
        ytc = YouTubeController()
        cast.register_handler(ytc)
        print("\n\nConnected to: " + chromeCastName + "!")
    except StopIteration:
        print("\n\n" + chromeCastName +
              " not found, vids will be displayed on this screen")
        chromeCast = False

#set up system variables for specific drafting sites
if "sleeper" in site.lower():
    import time
    site = "sleeper"
    sApi = "https://api.sleeper.app/v1/draft/" + str(boardNum) + "/picks"
    from vDictSleeper import vDictSleeper as vDict
elif "clicky" in site.lower():
    site = "clicky"
    from vDictClicky import vDictClicky as vDict
elif "basmith7" in site.lower():
    import time
Example #17
0
 def __init__(self, cc: Chromecast):
   self.cc = cc
   self.yt_ctl = YouTubeController()
   self.cc.register_handler(self.yt_ctl)
Example #18
0
class YoutubeCastController(CastController, MediaControllerMixin, PlaybackBaseMixin):
    def __init__(self, cast, app, prep=None):
        self._controller = YouTubeController()
        super(YoutubeCastController, self).__init__(cast, app, prep=prep)
        self.info_type = "id"
        self.save_capability = "partial"
        self.playlist_capability = "complete"

    def play_media_id(self, video_id):
        self._controller.play_video(video_id)

    def play_playlist(self, playlist_id, video_id):
        self.clear()
        self._controller.play_video(video_id, playlist_id)

    def add(self, video_id):
        # You can't add videos to the queue while the app is buffering.
        self.wait_for(["BUFFERING"], invert=True)
        self._controller.add_to_queue(video_id)

    def add_next(self, video_id):
        self.wait_for(["BUFFERING"], invert=True)
        self._controller.play_next(video_id)

    def remove(self, video_id):
        self.wait_for(["BUFFERING"], invert=True)
        self._controller.remove_video(video_id)

    def clear(self):
        self._controller.clear_playlist()

    def restore(self, data):
        self.play_media_id(data["content_id"])
        self.wait_for(["PLAYING"])
        self.seek(data["current_time"])
Example #19
0
 def __init__(self, cast, app, prep=None):
     self._controller = YouTubeController()
     super(YoutubeCastController, self).__init__(cast, app, prep=prep)
     self.info_type = "id"
     self.save_capability = "partial"
     self.playlist_capability = "complete"
Example #20
0
class YoutubeCastController(CastController, MediaControllerMixin, PlaybackBaseMixin):
    def __init__(self, cast, app, prep=None):
        self._controller = YouTubeController()
        super(YoutubeCastController, self).__init__(cast, app, prep=prep)
        self.info_type = "id"
        self.save_capability = "partial"
        self.playlist_capability = "complete"

    def play_media_id(self, video_id):
        self._controller.play_video(video_id)

    def play_playlist(self, playlist_id, video_id):
        self.clear()
        self._controller.play_video(video_id, playlist_id)

    def add(self, video_id):
        # You can't add videos to the queue while the app is buffering.
        self.wait_for(["BUFFERING"], invert=True)
        self._controller.add_to_queue(video_id)

    def add_next(self, video_id):
        self.wait_for(["BUFFERING"], invert=True)
        self._controller.play_next(video_id)

    def remove(self, video_id):
        self.wait_for(["BUFFERING"], invert=True)
        self._controller.remove_video(video_id)

    def clear(self):
        self._controller.clear_playlist()

    def restore(self, data):
        self.play_media_id(data["content_id"])
        self.wait_for(["PLAYING"])
        self.seek(data["current_time"])
Example #21
0
from __future__ import print_function
import time
import pychromecast
print( "\r\nGetting Devices" )
devices = pychromecast.get_chromecasts_as_dict().keys()
print( devices )

selectedDevice = list(devices)[0]
selectedDevice = "Nate PC Right"
print( "\r\nUsing Device: "+selectedDevice )

#exit()

cast = pychromecast.get_chromecast(friendly_name=selectedDevice)
print(cast.device)
print(cast.status)
mc = cast.media_controller
print(mc.status)
mc.stop()
time.sleep(5)
mc.pause()
time.sleep(5)
mc.play()
from pychromecast.controllers.youtube import YouTubeController
yt = YouTubeController()
cast.register_handler(yt)

#yt.play_video("Xw8XCxWWTDg")
#yt.play_video("Nr_5Y6JKPc0")
#yt.play_video("YiUdrIsqmyQ")
yt.play_video("O5RdMvgk8b0")
Example #22
0
    def play(self,
             resource,
             content_type=None,
             chromecast=None,
             title=None,
             image_url=None,
             autoplay=True,
             current_time=0,
             stream_type=STREAM_TYPE_BUFFERED,
             subtitles=None,
             subtitles_lang='en-US',
             subtitles_mime='text/vtt',
             subtitle_id=1):
        """
        Cast media to a visible Chromecast

        :param resource: Media to cast
        :type resource: str

        :param content_type: Content type as a MIME type string
        :type content_type: str

        :param chromecast: Chromecast to cast to. If none is specified, then the default configured Chromecast
            will be used.
        :type chromecast: str

        :param title: Optional title
        :type title: str

        :param image_url: URL of the image to use for the thumbnail
        :type image_url: str

        :param autoplay: Set it to false if you don't want the content to start playing immediately (default: true)
        :type autoplay: bool

        :param current_time: Time to start the playback in seconds (default: 0)
        :type current_time: int

        :param stream_type: Type of stream to cast. Can be BUFFERED (default), LIVE or UNKNOWN
        :type stream_type: str

        :param subtitles: URL of the subtitles to be shown
        :type subtitles: str

        :param subtitles_lang: Subtitles language (default: en-US)
        :type subtitles_lang: str

        :param subtitles_mime: Subtitles MIME type (default: text/vtt)
        :type subtitles_mime: str

        :param subtitle_id: ID of the subtitles to be loaded (default: 1)
        :type subtitle_id: int
        """

        from pychromecast.controllers.youtube import YouTubeController
        if not chromecast:
            chromecast = self.chromecast

        post_event(MediaPlayRequestEvent, resource=resource, device=chromecast)
        cast = self.get_chromecast(chromecast)

        mc = cast.media_controller
        yt = self._get_youtube_url(resource)

        if yt:
            self.logger.info('Playing YouTube video {} on {}'.format(
                yt, chromecast))

            hndl = YouTubeController()
            cast.register_handler(hndl)
            hndl.update_screen_id()
            return hndl.play_video(yt)

        resource = self._get_resource(resource)

        if not content_type:
            content_type = get_mime_type(resource)

        if not content_type:
            raise RuntimeError(
                'content_type required to process media {}'.format(resource))

        if not resource.startswith('http://') and \
                not resource.startswith('https://'):
            resource = self.start_streaming(resource).output['url']
            self.logger.info(
                'HTTP media stream started on {}'.format(resource))

        self.logger.info('Playing {} on {}'.format(resource, chromecast))

        mc.play_media(resource,
                      content_type,
                      title=title,
                      thumb=image_url,
                      current_time=current_time,
                      autoplay=autoplay,
                      stream_type=stream_type,
                      subtitles=subtitles,
                      subtitles_lang=subtitles_lang,
                      subtitles_mime=subtitles_mime,
                      subtitle_id=subtitle_id)

        if subtitles:
            mc.register_status_listener(
                self.SubtitlesAsyncHandler(mc, subtitle_id))

        mc.block_until_active()

        if self.volume:
            self.set_volume(volume=self.volume, chromecast=chromecast)

        return self.status(chromecast=chromecast)
Example #23
0
"""
Example on how to use the YouTube Controller

"""

import pychromecast
from pychromecast.controllers.youtube import YouTubeController


# Change to the name of your Chromecast
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 = ""


chromecasts = pychromecast.get_chromecasts()
cast = next(cc for cc in chromecasts if cc.device.friendly_name == CAST_NAME)
cast.wait()
yt = YouTubeController()
cast.register_handler(yt)
yt.play_video(VIDEO_ID)