def done(title, dest, downloaded):
playing = xbmc.Player().isPlaying()
text = xbmcgui.Window(10000).getProperty('GEN-DOWNLOADED')
if len(text) > 0:
text += '[CR]'
if downloaded:
text += '%s : %s' % (dest.rsplit(os.sep)[-1], '[COLOR forestgreen]Download succeeded[/COLOR]')
else:
text += '%s : %s' % (dest.rsplit(os.sep)[-1], '[COLOR red]Download failed[/COLOR]')
xbmcgui.Window(10000).setProperty('GEN-DOWNLOADED', text)
if (not downloaded) or (not playing):
xbmcgui.Dialog().ok(title, text)
xbmcgui.Window(10000).clearProperty('GEN-DOWNLOADED')
python类Player()的实例源码
def play(self, item='', listitem=None, windowed=False, sublist=None):
self._sublist = sublist
super(Player, self).play(item, listitem, windowed)
self._start_time = time.time()
while True:
# ???????????5???????????kodi???????
if self._stopped or time.time() - self._start_time > 300:
if self._totalTime == 999999:
raise PlaybackFailed(
'XBMC silently failed to start playback')
break
xbmc.sleep(500)
# print 'play end'
def play_playlist(self):
'''play entire playlist'''
if not self.local_playback:
self.connect_playback()
else:
playlistdetails = self.get_playlist_details(self.ownerid, self.playlistid)
kodi_playlist = xbmc.PlayList(0)
kodi_playlist.clear()
kodi_player = xbmc.Player()
# add first track and start playing
url, li = parse_spotify_track(playlistdetails["tracks"]["items"][0])
kodi_playlist.add(url, li)
kodi_player.play(kodi_playlist)
# add remaining tracks to the playlist while already playing
for track in playlistdetails["tracks"]["items"][1:]:
url, li = parse_spotify_track(track)
kodi_playlist.add(url, li)
def done(title, dest, downloaded):
playing = xbmc.Player().isPlaying()
text = xbmcgui.Window(10000).getProperty('GEN-DOWNLOADED')
if len(text) > 0:
text += '[CR]'
if downloaded:
text += '%s : %s' % (dest.rsplit(os.sep)[-1], '[COLOR forestgreen]Download succeeded[/COLOR]')
else:
text += '%s : %s' % (dest.rsplit(os.sep)[-1], '[COLOR red]Download failed[/COLOR]')
xbmcgui.Window(10000).setProperty('GEN-DOWNLOADED', text)
if (not downloaded) or (not playing):
xbmcgui.Dialog().ok(title, text)
xbmcgui.Window(10000).clearProperty('GEN-DOWNLOADED')
def direct_play(url):
_log("direct_play ["+url+"]")
title = ""
try:
xlistitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", path=url)
except:
xlistitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", )
xlistitem.setInfo( "video", { "Title": title } )
playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
playlist.clear()
playlist.add( url, xlistitem )
player_type = xbmc.PLAYER_CORE_AUTO
xbmcPlayer = xbmc.Player( player_type )
xbmcPlayer.play(playlist)
def direct_play(url):
_log("direct_play ["+url+"]")
title = ""
try:
xlistitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", path=url)
except:
xlistitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", )
xlistitem.setInfo( "video", { "Title": title } )
playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
playlist.clear()
playlist.add( url, xlistitem )
player_type = xbmc.PLAYER_CORE_AUTO
xbmcPlayer = xbmc.Player( player_type )
xbmcPlayer.play(playlist)
def done(title, dest, downloaded):
playing = xbmc.Player().isPlaying()
text = xbmcgui.Window(10000).getProperty('GEN-DOWNLOADED')
if len(text) > 0:
text += '[CR]'
if downloaded:
text += '%s : %s' % (dest.rsplit(os.sep)[-1], '[COLOR forestgreen]Download succeeded[/COLOR]')
else:
text += '%s : %s' % (dest.rsplit(os.sep)[-1], '[COLOR red]Download failed[/COLOR]')
xbmcgui.Window(10000).setProperty('GEN-DOWNLOADED', text)
if (not downloaded) or (not playing):
xbmcgui.Dialog().ok(title, text)
xbmcgui.Window(10000).clearProperty('GEN-DOWNLOADED')
def done(title, dest, downloaded):
playing = xbmc.Player().isPlaying()
text = xbmcgui.Window(10000).getProperty('GEN-DOWNLOADED')
if len(text) > 0:
text += '[CR]'
if downloaded:
text += '%s : %s' % (dest.rsplit(os.sep)[-1], '[COLOR forestgreen]Download succeeded[/COLOR]')
else:
text += '%s : %s' % (dest.rsplit(os.sep)[-1], '[COLOR red]Download failed[/COLOR]')
xbmcgui.Window(10000).setProperty('GEN-DOWNLOADED', text)
if (not downloaded) or (not playing):
xbmcgui.Dialog().ok(title, text)
xbmcgui.Window(10000).clearProperty('GEN-DOWNLOADED')
def timeRatio(self):
if self.isPlayingVideo():
self.watchedTime = self.getTime()
self.itemDuration = self.getTotalTime()
try:
util.debug("[SC] watched %f duration %f" % (self.watchedTime, self.itemDuration))
return float("%.3f" % (self.watchedTime / math.floor(self.itemDuration)))
except Exception, e:
util.debug("[SC] timeRatio error")
util.debug(e)
pass
try:
self.realFinishTime = xbmc.getInfoLabel('Player.FinishTime(hh:mm:ss)')
return (self.get_sec(self.estimateFinishTime).seconds - \
self.get_sec(self.realFinishTime).seconds) / \
math.floor(self.itemDuration)
except:
return None
def done(title, dest, downloaded):
playing = xbmc.Player().isPlaying()
text = xbmcgui.Window(10000).getProperty('GEN-DOWNLOADED')
if len(text) > 0:
text += '[CR]'
if downloaded:
text += '%s : %s' % (dest.rsplit(os.sep)[-1], '[COLOR forestgreen]Download succeeded[/COLOR]')
else:
text += '%s : %s' % (dest.rsplit(os.sep)[-1], '[COLOR red]Download failed[/COLOR]')
xbmcgui.Window(10000).setProperty('GEN-DOWNLOADED', text)
if (not downloaded) or (not playing):
xbmcgui.Dialog().ok(title, text)
xbmcgui.Window(10000).clearProperty('GEN-DOWNLOADED')
def direct_play(url):
_log("direct_play ["+url+"]")
title = ""
try:
xlistitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", path=url)
except:
xlistitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", )
xlistitem.setInfo( "video", { "Title": title } )
playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
playlist.clear()
playlist.add( url, xlistitem )
player_type = xbmc.PLAYER_CORE_AUTO
xbmcPlayer = xbmc.Player( player_type )
xbmcPlayer.play(playlist)
def doPlay():
if not configureTMDB():
return
dbid = getDbId()
imdbnumber = getIMDBNumber()
mediatype = getMediaType()
xbmcgui.Dialog().notification(ADDON.getLocalizedString(32009), sys.listitem.getLabel(), xbmcgui.NOTIFICATION_INFO, 3000)
log.debug("Playing for: DBID=%s, IMDB=%s, MediaType=%s" % (dbid, imdbnumber, mediatype))
if mediatype == 'movie':
tmdb_id = getTMDBId('movie', imdbnumber)
url = "plugin://plugin.video.quasar/library/movie/play/%s" % tmdb_id
elif mediatype == 'episode':
(show_id, season_number, episode_number) = getEpisodeDetails()
tmdb_id = getTMDBId('show', show_id)
url = "plugin://plugin.video.quasar/library/show/play/%s/%s/%s" % (tmdb_id, season_number, episode_number)
log.debug("Fetched TMDB: %s" % tmdb_id)
if tmdb_id is not None:
log.debug("Starting Quasar with: %s" % url)
xbmc.Player().play(url)
plugintools.py 文件源码
项目:plugin.video.streamondemand-pureita
作者: orione7
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def direct_play(url):
_log("direct_play ["+url+"]")
title = ""
try:
xlistitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", path=url)
except:
xlistitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", )
xlistitem.setInfo( "video", { "Title": title } )
playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
playlist.clear()
playlist.add( url, xlistitem )
player_type = xbmc.PLAYER_CORE_AUTO
xbmcPlayer = xbmc.Player( player_type )
xbmcPlayer.play(playlist)
def play_vod(video_id):
"""
Play a video by the provided path.
:param path: str
:return: None
"""
f = urllib2.urlopen('http://www.zhanqi.tv/api/static/video.videoid/{video_id}.json?_v='.format(video_id=video_id))
obj = json.loads(f.read())
#path = 'http://dlhls.cdn.zhanqi.tv/zqlive/{video}.m3u8'.format(video=obj['data']['videoIdKey']);
#path = 'http://ebithdl.cdn.zhanqi.tv/zqlive/{video}.flv'.format(video=obj['data']['videoIdKey'])
path = '{VideoUrl}{VideoID}'.format(VideoUrl=obj['data']['flashvars']['VideoUrl'], VideoID=obj['data']['flashvars']['VideoID'])
#xbmc.log("------------------", 1)
#xbmc.log(path, 1)
#xbmc.log("------------------", 1)
play_item = xbmcgui.ListItem(path=path, thumbnailImage=obj['data']['bpic'])
play_item.setInfo(type="Video", infoLabels={"Title":obj['data']['title']})
# Pass the item to the Kodi player.
xbmcplugin.setResolvedUrl(_handle, True, listitem=play_item)
# directly play the item.
xbmc.Player().play(path, play_item)
def play_video(room_id):
"""
Play a video by the provided path.
:param path: str
:return: None
"""
f = urllib2.urlopen('http://www.zhanqi.tv/api/static/live.roomid/{room_id}.json?sid='.format(room_id=room_id))
obj = json.loads(f.read())
#path = 'http://dlhls.cdn.zhanqi.tv/zqlive/{video}.m3u8'.format(video=obj['data']['videoIdKey']);
#path = 'http://ebithdl.cdn.zhanqi.tv/zqlive/{video}.flv'.format(video=obj['data']['videoIdKey'])
path = 'rtmp://wsrtmp.load.cdn.zhanqi.tv/zqlive/{video}'.format(video=obj['data']['videoIdKey'])
play_item = xbmcgui.ListItem(path=path, thumbnailImage=obj['data']['bpic'])
play_item.setInfo(type="Video", infoLabels={"Title":obj['data']['title']})
# Pass the item to the Kodi player.
xbmcplugin.setResolvedUrl(_handle, True, listitem=play_item)
# directly play the item.
xbmc.Player().play(path, play_item)
def process_clicked_item(self, clicked_item):
if isinstance(clicked_item, xbmcgui.ListItem ):
di_url=clicked_item.getProperty('onClick_action') #this property is created when assembling the kwargs.get("listing") for this class
item_type=clicked_item.getProperty('item_type').lower()
elif isinstance(clicked_item, xbmcgui.ControlButton ):
#buttons have no setProperty() hiding it in Label2 no good.
#ast.literal_eval(cxm_string):
#di_url=clicked_item.getLabel2()
#log(' button label2='+repr(di_url))
#item_type=clicked_item.getProperty('item_type').lower()
pass
log( " clicked %s IsPlayable=%s url=%s " %( repr(clicked_item),item_type, di_url ) )
if item_type=='playable':
#a big thank you to spoyser (http://forum.kodi.tv/member.php?action=profile&uid=103929) for this help
pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
pl.clear()
pl.add(di_url, clicked_item)
xbmc.Player().play(pl, windowed=False)
elif item_type=='script':
#if user clicked on 'next' we close this screen and load the next page.
if 'mode=listSubReddit' in di_url:
self.busy_execute_sleep(di_url,500,True )
else:
self.busy_execute_sleep(di_url,3000,False )
def onClick(self, controlID):
clicked_control=self.getControl(controlID)
#log('clicked on controlID='+repr(controlID))
#button control does not have a property, we use a different method.
value_to_search=clicked_control.getLabel() #we'll just use the Property('link_url') that we used as button label to search
listitems=self.listing
li = next(l for l in listitems if l.getProperty('link_url') == value_to_search)
item_type=li.getProperty('item_type')
di_url=li.getProperty('onClick_action')
log( " clicked %s IsPlayable=%s url=%s " %( repr(clicked_control),item_type, di_url ) )
if item_type=='playable':
#a big thank you to spoyser (http://forum.kodi.tv/member.php?action=profile&uid=103929) for this help
pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
pl.clear()
pl.add(di_url, value_to_search)
xbmc.Player().play(pl, windowed=False)
elif item_type=='script':
self.busy_execute_sleep(di_url,5000,False)
def playVideo(url, name, type_):
xbmc_busy(False)
pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
pl.clear()
if url : #sometimes url is a list of url or just a single string
if isinstance(url, basestring):
pl.add(url, xbmcgui.ListItem(name))
xbmc.Player().play(pl, windowed=False) #scripts play video like this.
#listitem = xbmcgui.ListItem(path=url) #plugins play video like this.
#xbmcplugin.setResolvedUrl(pluginhandle, True, listitem)
else:
for u in url:
#log('u='+ repr(u))
#pl.add(u)
pl.add(u, xbmcgui.ListItem(name))
xbmc.Player().play(pl, windowed=False)
else:
log("playVideo(url) url is blank")
def _set_resolved_url(self, context, base_item, succeeded=True):
item = xbmc_items.to_item(context, base_item)
item.setPath(base_item.get_uri())
xbmcplugin.setResolvedUrl(self.handle, succeeded=succeeded, listitem=item)
"""
# just to be sure :)
if not isLiveStream:
tries = 100
while tries>0:
xbmc.sleep(50)
if xbmc.Player().isPlaying() and xbmc.getCondVisibility("Player.Paused"):
xbmc.Player().pause()
break
tries-=1
"""
def play(self, playlist_index=-1):
"""
We call the player in this way, because 'Player.play(...)' will call the addon again while the instance is
running. This is somehow shitty, because we couldn't release any resources and in our case we couldn't release
the cache. So this is the solution to prevent a locked database (sqlite).
"""
self._context.execute('Playlist.PlayOffset(%s,%d)' % (self._player_type, playlist_index))
"""
playlist = None
if self._player_type == 'video':
playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
elif self._player_type == 'music':
playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
if playlist_index >= 0:
xbmc.Player().play(item=playlist, startpos=playlist_index)
else:
xbmc.Player().play(item=playlist)
"""
def _get_tags( self ):
# get track tags
artist = self.getMusicInfoTag().getArtist()
album = self.getMusicInfoTag().getAlbum()
title = self.getMusicInfoTag().getTitle()
duration = str(self.getMusicInfoTag().getDuration())
# get duration from xbmc.Player if the MusicInfoTag duration is invalid
if int(duration) <= 0:
duration = str(int(self.getTotalTime()))
track = str(self.getMusicInfoTag().getTrack())
mbid = '' # musicbrainz id is not available
comment = self.getMusicInfoTag().getComment()
path = self.getPlayingFile()
timestamp = int(time.time())
source = 'P'
# streaming radio of provides both artistname and songtitle as one label
if title and not artist:
try:
artist = title.split(' - ')[0]
title = title.split(' - ')[1]
except:
pass
tracktags = [artist, album, title, duration, track, mbid, comment, path, timestamp, source]
log('#DEBUG# tracktags: %s' % tracktags)
return tracktags
def init(self):
self._closed = False
self._nextItem = None
self.started = False
self.video = None
self.hasOSD = False
self.hasSeekOSD = False
self.handler = AudioPlayerHandler(self)
self.playerObject = None
self.currentTime = 0
self.thread = None
if xbmc.getCondVisibility('Player.HasMedia'):
self.started = True
self.open()
return self
def playAt(self, path, ms):
"""
Plays the video specified by path.
Optionally set the start position with h,m,s,ms keyword args.
"""
seconds = ms / 1000.0
h = int(seconds / 3600)
m = int((seconds % 3600) / 60)
s = int(seconds % 60)
ms = int((seconds % 1) * 1000)
kodijsonrpc.rpc.Player.Open(
item={'file': path},
options={'resume': {'hours': h, 'minutes': m, 'seconds': s, 'milliseconds': ms}}
)
def _monitor(self):
try:
while not xbmc.abortRequested and not self._closed:
if not self.isPlaying():
util.DEBUG_LOG('Player: Idling...')
while not self.isPlaying() and not xbmc.abortRequested and not self._closed:
util.MONITOR.waitForAbort(0.1)
if self.isPlayingVideo():
util.DEBUG_LOG('Monitoring video...')
self._videoMonitor()
elif self.isPlayingAudio():
util.DEBUG_LOG('Monitoring audio...')
self._audioMonitor()
elif self.isPlaying():
util.DEBUG_LOG('Monitoring pre-play...')
self._preplayMonitor()
self.handler.close()
self.close()
util.DEBUG_LOG('Player: Closed')
finally:
self.trigger('session.ended')
def _set_resolved_url(self, context, base_item, succeeded=True):
item = xbmc_items.to_item(context, base_item)
item.setPath(base_item.get_uri())
xbmcplugin.setResolvedUrl(context.get_handle(), succeeded=succeeded, listitem=item)
"""
# just to be sure :)
if not isLiveStream:
tries = 100
while tries>0:
xbmc.sleep(50)
if xbmc.Player().isPlaying() and xbmc.getCondVisibility("Player.Paused"):
xbmc.Player().pause()
break
tries-=1
"""
def play(self, playlist_index=-1):
"""
We call the player in this way, because 'Player.play(...)' will call the addon again while the instance is
running. This is somehow shitty, because we couldn't release any resources and in our case we couldn't release
the cache. So this is the solution to prevent a locked database (sqlite).
"""
self._context.execute('Playlist.PlayOffset(%s,%d)' % (self._player_type, playlist_index))
"""
playlist = None
if self._player_type == 'video':
playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
pass
elif self._player_type == 'music':
playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
pass
if playlist_index >= 0:
xbmc.Player().play(item=playlist, startpos=playlist_index)
else:
xbmc.Player().play(item=playlist)
pass
"""
pass
def direct_play(url):
_log("direct_play ["+url+"]")
title = ""
try:
xlistitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", path=url)
except:
xlistitem = xbmcgui.ListItem( title, iconImage="DefaultVideo.png", )
xlistitem.setInfo( "video", { "Title": title } )
playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
playlist.clear()
playlist.add( url, xlistitem )
player_type = xbmc.PLAYER_CORE_AUTO
xbmcPlayer = xbmc.Player( player_type )
xbmcPlayer.play(playlist)
def __init__ (self):
xbmc.Player.__init__(self)
def __init__(self):
self._stopped = False
self._totalTime = 999999
xbmc.Player.__init__(self, xbmc.PLAYER_CORE_AUTO)
def quality(filepath):
if plugin.get_setting('show_stream_type', bool):
stream_type = ['M3U8_AUTO_720', 'NONE']
choice = dialog.select(u'?????', [u'??',u'??'])
if choice < 0:
return
elif choice == 0:
stream = stream_type[choice]
elif choice == 1:
stream = False
elif plugin.get_setting('stream_type', str) == 'NONE':
stream = False
else:
stream = plugin.get_setting('stream_type', str)
if isinstance(filepath, str):
filepath = filepath.decode('utf-8')
video_path = playlist_path(filepath, stream)
name = os.path.basename(filepath)
listitem = xbmcgui.ListItem(name)
listitem.setInfo(type='Video', infoLabels={'Title': name})
if video_path:
xbmc.Player().play(video_path, listitem, windowed=False)