Exemple #1
0
class audio_player:
    def __init__(self, mediapath = ''):
        self.mediapath = mediapath
        self.instance = Instance('--input-repeat=-1')
        self.player = self.instance.media_player_new()
        self.media = self.instance.media_new(self.mediapath)
        self.player.set_media(self.media)
        self.volume = 0
        self.playing = False

    def load(self, mediapath):
        if self.mediapath != mediapath:
            self.mediapath = mediapath
            self.media = self.instance.media_new(self.mediapath)
            self.player.set_media(self.media)

    def play(self):
        if !self.playing:
            self.player.play()

    def pause(self):
        if self.playing:
            self.player.pause()

    def setvol(self, vol):
         if vol != self.volume:
             self.player.audio_set_volume(vol)
class VLC:  # Crea instancia de VLC
    def __init__(self):
        self.Player = Instance('--loop')  #lo genera en modo bucle

    def addPlaylist(
            self, op
    ):  #agrega a la lista de reproduccion dependiendo el tipo de archivo
        self.mediaList = self.Player.media_list_new(
        )  #crea lista de reproduccion vacia

        path = r"/home/pi/Desktop/PFE"
        songs = os.listdir(path)  #crea lista de los archivos
        #        for x in songs:
        #
        #              print(x)
        for s in songs:  #filtra tipo de archivo dependiendo la eleccion
            if op == 1:  #fotos
                if '.jpg' in str(s) or 'png' in str(s) or 'jpeg' in str(s):
                    self.mediaList.add_media(
                        self.Player.media_new(os.path.join(path, s)))

            if op == 2:  #videos
                if '.mp4' in str(s) or '.avi' in str(s):
                    self.mediaList.add_media(
                        self.Player.media_new(os.path.join(path, s)))

            if op == 3:  #musica
                if '.mp3' in str(s):
                    self.mediaList.add_media(
                        self.Player.media_new(os.path.join(path, s)))
        self.listPlayer = self.Player.media_list_player_new(
        )  #crea lista de reproduccion vacia en la instancia de VLC
        self.listPlayer.set_media_list(
            self.mediaList
        )  #remplaza la lista de reproduccion de la instancia anterior con la nueva

    def play(self):  #reproduce
        self.listPlayer.play()

    def next(self):  #siguiente
        self.listPlayer.next()

    def pause(self):  #pausa
        self.listPlayer.pause()

    def previous(self):  #anterior
        self.listPlayer.previous()

    def stop(self):  #Alto
        self.listPlayer.stop()

    def playpause(self):  #itera entre reproducir y pausar
        if self.listPlayer.is_playing():
            self.stop()
        else:
            self.play()
Exemple #3
0
    def start_with_marquee(self, timeout=60):
        """这种方案是可以带字幕的,根据vlc自带测试源码改写"""

        movie = self.url
        # Need --sub-source=marq in order to use marquee below
        print(sys.argv[:])
        instance = Instance(["--sub-source=marq"] + sys.argv[1:])
        try:
            media = instance.media_new(movie)
        except (AttributeError, NameError) as e:
            sys.exit(1)
        player = instance.media_player_new()
        player.set_media(media)
        player.play()

        # Some marquee examples.  Marquee requires '--sub-source marq' in the
        # Instance() call above, see <http://www.videolan.org/doc/play-howto/en/ch04.html>
        player.video_set_marquee_int(VideoMarqueeOption.Enable, 1)
        player.video_set_marquee_int(VideoMarqueeOption.Size, 24)  # pixels
        player.video_set_marquee_int(VideoMarqueeOption.Position, Position.Bottom)
        player.video_set_marquee_int(VideoMarqueeOption.Timeout, 0)  # millisec, 0==forever
        player.video_set_marquee_int(VideoMarqueeOption.Refresh, 1000)  # millisec (or sec?)
        # t = '$L / $D or $P at $T'
        t = '%Y-%m-%d  %H:%M:%S'
        player.video_set_marquee_string(VideoMarqueeOption.Text, str_to_bytes(t))

        # Some event manager examples.  Note, the callback can be any Python
        # callable and does not need to be decorated.  Optionally, specify
        # any number of positional and/or keyword arguments to be passed
        # to the callback (in addition to the first one, an Event instance).
        event_manager = player.event_manager()
        event_manager.event_attach(EventType.MediaPlayerEndReached, end_callback)
        event_manager.event_attach(EventType.MediaPlayerPositionChanged, pos_callback, player)
        time.sleep(timeout)
class VLC:
    def __init__(self):
        self.Player = Instance('--loop')

    def addPlaylist(self):
        self.mediaList = self.Player.media_list_new()
        path = "/Users/avni_aaron/Desktop/Classical_music"
        songs = os.listdir(path)
        for s in songs:
            self.mediaList.add_media(
                self.Player.media_new(os.path.join(path, s)))
        self.listPlayer = self.Player.media_list_player_new()
        self.listPlayer.set_media_list(self.mediaList)

    def play(self):
        self.listPlayer.play()

    def next(self):
        self.listPlayer.next()

    def pause(self):
        self.listPlayer.pause()

    def previous(self):
        self.listPlayer.previous()

    def stop(self):
        self.listPlayer.stop()

    def set_volume(self, vol):
        self.listPlayer.audio_set_volume(vol)
 def start(self, timeout=60):
     """这种是最简方案,用来测试播放足够了
   """
     instance = Instance()
     player = instance.media_player_new()
     Media = instance.media_new(self.url)
     mrl = Media.get_mrl()
     player.set_media(Media)
     event_manager = player.event_manager()
     event_manager.event_attach(EventType.MediaPlayerOpening,
                                self.open_callback)
     event_manager.event_attach(EventType.MediaPlayerPaused,
                                self.paused_callback)
     event_manager.event_attach(EventType.MediaListPlayerStopped,
                                self.media_list_stoped_callback)
     event_manager.event_attach(EventType.MediaParsedChanged,
                                self.media_buffering_callback)
     event_manager.event_attach(EventType.MediaPlayerStopped,
                                self.stoped_callback)
     event_manager.event_attach(EventType.MediaPlayerEndReached,
                                self.end_callback)
     event_manager.event_attach(
         EventType.VlmMediaInstanceStatusPause,
         self.vlm_media_instance_status_pause_callback)
     event_manager.event_attach(EventType.VlmMediaInstanceStatusError,
                                self.vlm_media_instance_error_callback)
     event_manager.event_attach(EventType.MediaPlayerPausableChanged,
                                self.media_player_pausable_callback)
     event_manager.event_attach(EventType.MediaPlayerPositionChanged,
                                self.pos_callback, player, Media)
     while self.start_status:
         player.play()  # 如果是看直播这里直接写while True 即可
         if player.get_state() == State.Stopped:
             for i in range(5):
                 player.play()
                 self.write_log(u"VLC播放停止了,第%d次尝试重连,总共尝试5次" % i)
                 if player.get_state() == State.Opening or player.get_state(
                 ) == State.Playing:
                     break
             break
         if player.get_state() == State.Ended:
             for i in range(5):
                 player.stop()
                 self.start()
                 self.write_log(u"VLC播放终止了,第%d次尝试重连,总共尝试5次" % i)
                 if player.get_state() == State.Opening or player.get_state(
                 ) == State.Playing:
                     break
             break
         if player.get_state() == State.Error:
             for i in range(5):
                 player.stop()
                 self.start()
                 self.write_log(u"VLC播放出错了,第%d次尝试重连,总共尝试5次" % i)
                 if player.get_state() == State.Opening or player.get_state(
                 ) == State.Playing:
                     break
             break
     player.stop()
Exemple #6
0
class Player:
    def __init__(self):
        self.Player = Instance('--loop --no-video')
        self.volume = 50
        self.listPlayer = None

    def setPlaylist(self, playlist):

        if self.listPlayer != None:
            self.listPlayer.stop()
            self.listPlayer.release()

        self.mediaList = self.Player.media_list_new()
        for song in playlist:
            self.mediaList.add_media(self.Player.media_new(song))
        self.listPlayer = self.Player.media_list_player_new()
        self.listPlayer.set_media_list(self.mediaList)
        self.listPlayer.get_media_player().audio_set_volume(self.volume)

    def play(self, index):
        self.listPlayer.play_item_at_index(index)

    def next(self):
        self.listPlayer.next()

    def pause(self):
        self.listPlayer.pause()

    def previous(self):
        self.listPlayer.previous()

    def stop(self):
        self.listPlayer.stop()

    def setPosition(self, v):
        self.listPlayer.get_media_player().set_position(v)

    def setVolume(self, v):
        self.volume = int(v * 100)
        if self.listPlayer != None:
            self.listPlayer.get_media_player().audio_set_volume(self.volume)

    def addToQueue(self, song):
        self.mediaList.add_media(self.Player.media_new(song))
Exemple #7
0
 def start(self, timeout=60):
     u"""这种是最简方案,用来测试播放足够了
       """
     instance = Instance()
     player = instance.media_player_new()
     Media = instance.media_new(self.url)
     Media.get_mrl()
     player.set_media(Media)
     player.play()  # 如果是看直播这里直接写while True 即可
     time.sleep(timeout)
Exemple #8
0
    def __init__(self, file, s=turtle.Screen(), e=1, color=1):
        self.screen = s
        self.elasticity = e
        self.avgLine = []
        self.color = color

        sound = AudioSegment.from_file(file, format=file[file.rfind(".") + 1:])
        outPath = "read.wav"
        sound.export(outPath, format="wav")

        instance = Instance()
        self.mediaPlayer = instance.media_player_new()
        self.mediaPlayer.set_media(instance.media_new(outPath))

        self.songFile = wave.open(outPath, 'r')
Exemple #9
0
def start_streaming_player(port: int, file: str):
    cmd = [
        "file://{}".format(file),
        "sout=#duplicate{dst=rtp{dst=127.0.0.1,port=" + str(port) + "}}",
        "no-sout-rtp-sap", "no-sout-standard-sap", "sout-keep"
    ]
    d("start streaming with arguments: {}".format(cmd))
    vlc = VLC()
    media = vlc.media_new(*cmd)
    media.get_mrl()

    player = vlc.media_player_new()
    player.set_media(media)
    player.play()

    return player
Exemple #10
0
    def __init__(self, file, s = turtle.Screen(), e = 1, color = 1):
        self.screen = s
        self.elasticity = e
        self.avgLine = []
        self.color = color
        
        sound = AudioSegment.from_file(
            file, format=file[file.rfind(".")+1:])
        outPath = "read.wav"
        sound.export(outPath, format = "wav")

        instance = Instance()
        self.mediaPlayer = instance.media_player_new()
        self.mediaPlayer.set_media(instance.media_new(outPath))

        self.songFile = wave.open(outPath, 'r')
    def start(self):
        #      这种是最简方案,用来测试播放足够了
        instance = Instance()
        player = instance.media_player_new()
        Media = instance.media_new(self.url)
        Media.get_mrl()
        player.set_media(Media)
        player.play()

        event_manager = player.event_manager()
        # 播放到视频结尾时,返回end_callback()方法
        # event_manager.event_attach(EventType.MediaPlayerEndReached, end_callback)
        # 播放进度发生改变时,继续播放视频并(在控制台)显示播放进度
        event_manager.event_attach(EventType.MediaPlayerPositionChanged,
                                   pos_callback, player)
        #         如果是视频,会在视频的最后一个画面停止
        while True:
            pass
Exemple #12
0
class testVLC:
    def __init__(self):
        self.list1 = playlist
        self.Player = Instance('--loop')

    def addPlaylist(self):
        self.mediaList = self.Player.media_list_new()
        for music in self.list1:
            self.mediaList.add_media(self.Player.media_new(music_dir+'/'+music))
        self.listPlayer = self.Player.media_list_player_new()
        self.listPlayer.set_media_list(self.mediaList)
    def playPlaylist(self):
        self.listPlayer.play()
    def nextPlay(self):
        self.listPlayer.next()
    def pausePlaylist(self):
        self.listPlayer.pause()
    def stopPlaylist(self):
        self.listPlayer.stop()
Exemple #13
0
    def __init__(self, vlc: Instance, url: str):
        with YoutubeDL({"format": self.__ydl_format}) as ydl:
            info = ydl.extract_info(url, download=False)

            self.title = info["title"]

            # This means there's the video got splitted up to
            # video-only and audio-only
            if "requested_formats" in info:
                formats = info["requested_formats"]

                # TODO! maybe the order of formats matters
                self.video_url = formats[0]["url"]
                self.audio_url = formats[1]["url"]
                self.has_audio = False
            else:
                self.video_url = info["url"]

            self.thumbnail_url = info["thumbnail"]

            self.media = vlc.media_new(self.video_url)
            if not self.has_audio:
                self.media.slaves_add(1, 4, self.audio_url)
Exemple #14
0
class Player(object):
    def __init__(self, device_id):
        self.api = Mobileclient()
        self.api.logger.setLevel(logging.INFO)
        #print(utils.log_filepath)

        options = ["--aout=alsa", "-I dummy", "--fullscreen"]
        self.vlc = Instance(options)
        self.player = None

        self.loaded_tracks = []

        self.playing = False
        self.repeat = Repeat.none
        self.random = False
        self.song_index = 0
        self.now_playing_title = ""
        self.now_playing_artist = ""
        self.now_playing_playlist = ""

        # 取得したjsonの生データ
        self.song_library = []
        self.playlist_library = []
        # 整頓した楽曲ライブラリ
        self.songs = []
        self.albums = []
        self.playlists = []
        self.artists = []

        # play musicログイン
        if not os.path.exists(CREDENTIAL_FILE):
            self.api.perform_oauth(CREDENTIAL_FILE)
        self.api.oauth_login(device_id, CREDENTIAL_FILE)
        # 曲一覧読み込み
        if os.path.isfile(JSON_DIR + "songs.json"):
            # Load from file
            print("Found songs data.")
            with open(JSON_DIR + 'songs.json') as input_file:
                self.song_library = json.load(input_file)
        else:
            self.song_library = self.api.get_all_songs()
            # Save to file
            with open(JSON_DIR + 'songs.json', 'w') as output_file:
                json.dump(self.song_library, output_file)

        self.create_songs()
        self.create_albums()
        self.create_artists()

        # プレイリスト読み込み
        if os.path.isfile(JSON_DIR + "playlists.json"):
            # Load from file
            print("Found playlist data.")
            with open(JSON_DIR + 'playlists.json') as input_file:
                self.playlist_library = json.load(input_file)
        else:
            self.playlist_library = self.api.get_all_user_playlist_contents()
            # Save to file
            with open(JSON_DIR + 'playlists.json', 'w') as output_file:
                json.dump(self.playlist_library, output_file)
        #プレイリスト名編集
        self.create_playlists()

        # 定時ライブラリ更新処理
        t = threading.Timer(RELOAD_LIB_TIME, self.auto_reload)
        t.start()

    def auto_reload(self):
        while True:
            if not self.playing:
                break
            time.sleep(60)
        self.reload_library()
        print("[ music list auto reloaded ]")
        t = threading.Timer(RELOAD_LIB_TIME, self.auto_reload)
        t.start()

    def reload_library(self):
        # 曲一覧読み込み
        self.song_library = self.api.get_all_songs()
        # Save to file
        with open(JSON_DIR + 'songs.json', 'w') as output_file:
            json.dump(self.song_library, output_file)

        self.create_songs()
        self.create_albums()
        self.create_artists()
        # プレイリスト読み込み
        self.playlist_library = self.api.get_all_user_playlist_contents()
        # Save to file
        with open(JSON_DIR + 'playlists.json', 'w') as output_file:
            json.dump(self.playlist_library, output_file)
        #プレイリスト名編集
        self.create_playlists()

    def create_songs(self):
        self.songs = []
        # 曲名編集
        for index, song in enumerate(self.song_library):
            self.songs.append({})
            self.songs[index].update({"original_name": song['title']})
            self.songs[index].update(
                {"name": cir.convert_into_romaji(song['title'])})
            self.songs[index].update({"artist": song['artist']})
            self.songs[index].update({"trackId": song['id']})
            self.songs[index].update({"source": 1})
            #print(self.songs[index])
            #sleep(0.1)
        print("[ create_songs finished ]")

    def create_playlists(self):
        self.playlists = []
        #プレイリスト名編集
        for index, playlist in enumerate(self.playlist_library):
            self.playlists.append({})
            self.playlists[index].update({"original_name": playlist['name']})
            self.playlists[index].update(
                {"name": cir.convert_into_romaji(playlist['name'])})
            self.playlists[index].update({"tracks": playlist['tracks']})
            print(self.playlists[index]['name'])
        print("[ create_playlists finished ]")

    def create_albums(self):
        self.albums = []
        # アルバムリスト作成
        for song in self.song_library:
            album_found = False
            track = {}
            for index, album in enumerate(self.albums):
                # アルバムがすでに登録されていた場合
                if album['original_name'] == song['album']:
                    album_found = True
                    track.update({"trackId": song['id']})
                    track.update({"source": 1})
                    track.update({"trackNumber": song['trackNumber']})
                    self.albums[index]['tracks'].append(track)
                    #print(self.albums[index])
                    break
            if album_found:
                continue

            #新規アルバム作成
            albums_len = len(self.albums)
            self.albums.append({})
            self.albums[albums_len].update({"original_name": song['album']})
            self.albums[albums_len].update(
                {"name": cir.convert_into_romaji(song['album'])})

            track.update({"trackId": song['id']})
            track.update({"source": 1})
            track.update({"trackNumber": song['trackNumber']})
            self.albums[albums_len].update({"tracks": [track]})
            #print(self.albums[albums_len])
        # tracknumberでソート
        for album in self.albums:
            album['tracks'] = sorted(album['tracks'],
                                     key=lambda x: x['trackNumber'])
            print(album["name"])

        print("[ create_albums finished ]")

    def create_artists(self):
        self.artists = []
        # アーティストリスト作成
        for song in self.song_library:
            artist_found = False
            track = {}
            for index, artist in enumerate(self.artists):
                # アーティストがすでに登録されていた場合
                if artist['original_name'] == song['artist']:
                    artist_found = True
                    track.update({"trackId": song['id']})
                    track.update({"source": 1})
                    track.update({"trackNumber": song['trackNumber']})
                    self.artists[index]['tracks'].append(track)
                    break
            if artist_found:
                continue

            #新規アルバム作成
            artists_len = len(self.artists)
            self.artists.append({})
            self.artists[artists_len].update({"original_name": song['artist']})
            self.artists[artists_len].update(
                {"name": cir.convert_into_romaji(song['artist'])})

            track.update({"trackId": song['id']})
            track.update({"source": 1})
            track.update({"trackNumber": song['trackNumber']})
            self.artists[artists_len].update({"tracks": [track]})
            print(self.artists[artists_len]["name"])
        print("[ create_artists finished ]")

    def load_playlist(self, name):
        name = name.strip().lower()
        print("Looking for...", name)

        top_diff = 0.0
        top_playlist = {}
        # 検索
        for playlist_dict in self.playlists:
            playlist_name = playlist_dict['name'].strip().lower()
            diff = difflib.SequenceMatcher(None, playlist_name, name).ratio()

            if diff > top_diff:
                print("diff match...", playlist_dict['name'], ":", diff)
                top_playlist = playlist_dict
                top_diff = diff
            else:
                pass
                #print("Found...", playlist_dict['name'])
        # 一番マッチしたものを返す
        if top_diff > DIFF_ARGS:
            self.loaded_tracks = []
            print(top_diff)
            print("Found match...", top_playlist['name'])
            for track_dict in top_playlist['tracks']:
                self.loaded_tracks.append(track_dict)
            self.now_playing_playlist = top_playlist['original_name']
            return top_playlist['original_name']
        else:
            return None

    def load_song(self, name):
        name = name.strip().lower()
        print("Looking for...", name)

        top_diff = 0.0
        top_song = {}
        for song_dict in self.songs:
            song_name = song_dict['name'].strip().lower()
            diff = difflib.SequenceMatcher(None, song_name, name).ratio()
            #print(diff)
            if diff > top_diff:
                print("diff match...", song_dict['name'], ":", diff)
                top_song = song_dict
                top_diff = diff
            else:
                pass
                #print("Found...", song_dict['name'])
        # 一番マッチしたものを返す
        if top_diff > DIFF_ARGS:
            self.loaded_tracks = []
            print(top_diff)
            print("Found match...", top_song['name'])
            self.loaded_tracks.append(top_song)
            self.now_playing_playlist = ""
            return top_song['original_name']
        else:
            return None

    def load_album(self, name):
        name = name.strip().lower()
        print("Looking for...", name)

        top_diff = 0.0
        top_album = {}
        for album_dict in self.albums:
            album_name = album_dict['name'].strip().lower()
            diff = difflib.SequenceMatcher(None, album_name, name).ratio()
            #print(diff)
            if diff > top_diff:
                print("diff match...", album_dict['name'], ":", diff)
                top_album = album_dict
                top_diff = diff
            else:
                pass
                #print("Found...", album_dict['name'])
        # 一番マッチしたものを返す
        if top_diff > DIFF_ARGS:
            self.loaded_tracks = []
            print(top_diff)
            print("Found match...", top_album['name'])
            for track_dict in top_album['tracks']:
                self.loaded_tracks.append(track_dict)
            self.now_playing_playlist = top_album['original_name']
            return top_album['original_name']
        else:
            return None

    def load_artist(self, name):
        name = name.strip().lower()
        print("Looking for...", name)

        top_diff = 0.0
        top_artist = {}
        for artist_dict in self.artists:
            artist_name = artist_dict['name'].strip().lower()
            diff = difflib.SequenceMatcher(None, artist_name, name).ratio()
            #print(diff)
            if diff > top_diff:
                print("diff match...", artist_dict['name'], ":", diff)
                top_artist = artist_dict
                top_diff = diff
            else:
                pass
        # 一番マッチしたものを返す
        if top_diff > DIFF_ARGS:
            self.loaded_tracks = []
            print(top_diff)
            print("Found match...", top_artist['name'])
            for track_dict in top_artist['tracks']:
                self.loaded_tracks.append(track_dict)
            self.now_playing_playlist = top_artist['original_name']
            return top_artist['original_name']
        else:
            return None

    def load_cloud(self, name, isArtist=True, isSong=True, isAlbum=True):
        search = self.api.search(name)

        # アーティストのトップ曲を流す
        if search["artist_hits"] and isArtist:
            for index in range(len(search["artist_hits"])):
                artist_id = search["artist_hits"][index]["artist"]["artistId"]
                artist = self.api.get_artist_info(artist_id,
                                                  max_top_tracks=MAX_TRACK,
                                                  include_albums=False,
                                                  max_rel_artist=0)
                if "topTracks" in artist.keys():
                    break
            if "topTracks" in artist.keys():
                self.loaded_tracks = []
                for track_dict in artist["topTracks"]:
                    track_dict.update({"track": track_dict})
                    track_dict.update({"trackId": track_dict["storeId"]})
                    track_dict.update({"source": "2"})
                    self.loaded_tracks.append(track_dict)
                self.now_playing_playlist = ""
                return artist["name"]

        # 単曲を流す(複数にしたほうがいいかも)
        elif search["song_hits"] and isSong:
            self.loaded_tracks = []
            for index, track_dict in enumerate(search["song_hits"]):
                if index >= MAX_TRACK: break
                track_dict.update({"trackId": track_dict["track"]["storeId"]})
                track_dict.update({"source": "2"})
                self.loaded_tracks.append(track_dict)
            self.now_playing_playlist = ""
            return self.loaded_tracks[0]["track"]["title"]

        # アルバムを流す(正確さに欠ける)
        elif search["album_hits"] and isAlbum:
            album_id = search["album_hits"][0]["album"]["albumId"]
            album = self.api.get_album_info(album_id)
            self.loaded_tracks = []
            for track_dict in album["tracks"]:
                track_dict.update({"track": track_dict})
                track_dict.update({"trackId": track_dict["storeId"]})
                track_dict.update({"source": "2"})
                self.loaded_tracks.append(track_dict)
            self.now_playing_playlist = album["name"]
            return album["name"]

        # ステーション(ここまで回ってこない気が・・・)
        elif search["station_hits"]:
            pass
        return None

    def end_callback(self, event, track_index):
        # ランダム再生時処理
        if self.random:
            self.song_index = random.randint(0, len(self.loaded_tracks) - 1)
            self.play_song(self.loaded_tracks[self.song_index])
            event_manager = self.player.event_manager()
            event_manager.event_attach(EventType.MediaPlayerEndReached,
                                       self.end_callback, self.song_index + 1)
            return
        # 一曲リピート
        if self.repeat == Repeat.song:
            self.play_song(self.loaded_tracks[track_index - 1])
            event_manager = self.player.event_manager()
            event_manager.event_attach(EventType.MediaPlayerEndReached,
                                       self.end_callback, track_index)
            return
        # 通常再生・プレイリストリピート
        if track_index < len(self.loaded_tracks):
            self.song_index = track_index
            self.play_song(self.loaded_tracks[track_index])
            event_manager = self.player.event_manager()
            event_manager.event_attach(EventType.MediaPlayerEndReached,
                                       self.end_callback, track_index + 1)
        else:
            if self.repeat == Repeat.playlist:
                self.start_playlist()
            else:
                self.playing = False
                self.song_index = 0

    def start_playlist(self):
        if len(self.loaded_tracks) > 0:
            # ランダム再生時処理
            if self.random:
                self.song_index = random.randint(0,
                                                 len(self.loaded_tracks) - 1)
            else:
                # 通常再生
                self.song_index = 0
            self.play_song(self.loaded_tracks[self.song_index])
            event_manager = self.player.event_manager()
            event_manager.event_attach(EventType.MediaPlayerEndReached,
                                       self.end_callback, self.song_index + 1)
            return True
        return False

    def play_song(self, song_dict):
        stream_url = self.api.get_stream_url(song_dict['trackId'])
        self.player = self.vlc.media_player_new()
        media = self.vlc.media_new(stream_url)
        self.player.set_media(media)
        self.player.play()
        self.playing = True

        if (song_dict['source'] == '2'):
            self.now_playing_artist, self.now_playing_title = self.get_song_details(
                song_dict)
        else:
            self.now_playing_artist, self.now_playing_title = self.get_local_song_details(
                song_dict['trackId'])

        print("Playing...", self.now_playing_artist, " - ",
              self.now_playing_title)

    def stop(self):
        if self.player != None:
            self.player.stop()
            self.player = None
        self.playing = False
        self.repeat = Repeat.none
        self.random = False
        self.song_index = 0
        self.now_playing_title = ""
        self.now_playing_artist = ""

    def pause(self):
        if self.player == None:
            return False
        if self.playing == True:
            self.player.set_pause(1)
            self.playing = False
            return True
        return False

    def resume(self):
        if self.player == None:
            return False
        if self.playing == False:
            self.player.set_pause(0)
            self.playing = True
            return True
        return False

    def next(self):
        if self.player == None:
            return False
        # ランダム
        if self.random:
            self.song_index = random.randint(0, len(self.loaded_tracks) - 1)
            self.player.stop()
            self.play_song(self.loaded_tracks[self.song_index])
            event_manager = self.player.event_manager()
            event_manager.event_detach(EventType.MediaPlayerEndReached)
            event_manager.event_attach(EventType.MediaPlayerEndReached,
                                       self.end_callback, self.song_index + 1)
            return True
        # 通常
        if self.song_index + 1 < len(self.loaded_tracks):
            self.song_index += 1
            self.player.stop()
            self.play_song(self.loaded_tracks[self.song_index])
            event_manager = self.player.event_manager()
            event_manager.event_detach(EventType.MediaPlayerEndReached)
            event_manager.event_attach(EventType.MediaPlayerEndReached,
                                       self.end_callback, self.song_index + 1)
            return True
        else:
            if self.repeat == Repeat.playlist:
                self.start_playlist()
                return True

        return False

    def prev(self):
        if self.player == None:
            return False
        if self.song_index - 1 <= 0:
            self.song_index -= 1
            self.player.stop()
            self.play_song(self.loaded_tracks[self.song_index])
            event_manager = self.player.event_manager()
            event_manager.event_detach(EventType.MediaPlayerEndReached)
            event_manager.event_attach(EventType.MediaPlayerEndReached,
                                       self.end_callback, self.song_index + 1)
            return True
        return False

    def get_local_song_details(self, track_id):
        for song_dict in self.song_library:
            if track_id == song_dict['id']:
                return song_dict['artist'], song_dict['title']

    def get_song_details(self, song_dict):
        return song_dict['track']['albumArtist'], song_dict['track']['title']

    def set_volume(self, volume):
        if self.player:
            self.player.audio_set_volume(volume)
Exemple #15
0
class Player(object):

    def __init__(self, email, password, device_id):
        self.api = Mobileclient()
        self.vlc = Instance()
        self.loaded_tracks = []
        self.playing = False
        self.thread_running = False
        self.player = self.vlc.media_player_new()
        self.track_index = -1
        self.api.login(email, password, device_id)

    def load_song(self, name):
        name = name.strip().lower()
        print("Looking for song: ", name)
        if os.path.isfile("songs.json"):
            # Load from file
            print("Found songs data.")
            with open('songs.json') as input_file:
                self.song_library = json.load(input_file)
        else:
            self.song_library = self.api.get_all_songs()
            # Save to file
            with open('songs.json', 'w') as output_file:
                json.dump(self.song_library, output_file)    

        for song_dict in self.song_library:
            song_name = song_dict['title'].strip().lower()
            if (song_name == name) or (name in song_name):
                print("Found match: ", song_dict['title'])
                self.loaded_tracks.append(song_dict)
                return song_dict['title']
            else:
                print("Song not found :(")
        return None

    def load_playlist(self, name):
        name = name.strip().lower()
        print("Looking for playlist: ", name)
        if os.path.isfile("playlists.json"):
            # Load from file
            print("Found playlist data.")
            with open('playlists.json') as input_file:
                self.playlists = json.load(input_file)
        else:
            self.playlists = self.api.get_all_user_playlist_contents()
            # Save to file
            with open('playlists.json', 'w') as output_file:
                json.dump(self.playlists, output_file)
            
        self.loaded_tracks = []
        for playlist_dict in self.playlists:
            playlist_name = playlist_dict['name'].strip().lower()
            if (playlist_name == name) or (name in playlist_name):
                print("Found match...", playlist_dict['name'])
                for track_dict in playlist_dict['tracks']:
                    self.loaded_tracks.append(track_dict)
                return playlist_dict['name']
            else:
                print("Found...", playlist_dict['name'])
        return None
 
    def end_callback(self, event, track_index):
        if track_index < len(self.loaded_tracks):
            self.play_song(self.loaded_tracks[track_index])
            event_manager = self.player.event_manager()
            event_manager.event_attach(EventType.MediaPlayerEndReached, self.end_callback, track_index + 1)
            self.playing = True
        else:
            self.playing = False

    def start_playlist(self):
        if len(self.loaded_tracks) > 0:
            self.track_index = 0
            self.play_song(self.loaded_tracks[self.track_index])
        
            if len(self.loaded_tracks) > 1:
                event_manager = self.player.event_manager()
                event_manager.event_attach(EventType.MediaPlayerEndReached, self.end_callback, 1)
  
    def play_song(self, song_dict):
        stream_url = ""
        if 'trackId' in song_dict:
          stream_url = self.api.get_stream_url(song_dict['trackId'])
        else:
          stream_url = self.api.get_stream_url(song_dict['nid'])
        media = self.vlc.media_new(stream_url)
        self.player.set_media(media)
        self.player.play()

        song_string = ""
        # for playlists there are track dictionaries
        if 'track' in song_dict:
            song_string = song_dict['track']['artist'] + " - " + song_dict['track']['title']
        else:
            song_string = song_dict['artist'] + " - " + song_dict['title']
        print("Playing ", song_string)
        
        self.playing = True

    def stop(self):
        if self.player != None:
            self.player.stop()
        self.thread_running = False
        self.playing = False

    def toggle_pause(self):
        if self.player != None:
            self.player.pause()

    def next(self):
        if self.player != None:
            if self.track_index < (len(self.loaded_tracks) - 1):
                self.track_index += 1
                self.play_song(self.loaded_tracks[self.track_index])

    def previous(self):
        if self.player != None:
            if self.track_index > 0:
                self.track_index -= 1
                self.play_song(self.loaded_tracks[self.track_index])
Exemple #16
0
class Processor(object):



    def __init__(self,DEBUG = True, ACTIVE = ACTIVE):


        print("Loading VLC into memory")
        self.instance = Instance()

        print("Setting up Player")
        self.player = self.instance.media_player_new()



        self.ACTIVE = ACTIVE
        self.DEBUG = DEBUG
#        print('MY SCOPE:::',vars())


    def light_wrapper(func):
        def run_func(self,data):
            GPIO.output(11,True)
            func(self,data)
            GPIO.output(11,False)
            GPIO.cleanup
            return
     
        return run_func




    def raw_vlc_playback(self):
        if self.ACTIVE == False:
            return

        else:
#            print('PLAYING MEDIA')
            media = self.instance.media_new(my_file_name)
            self.player.set_media(media)
            self.player.play()
            return
#    @light_wrapper
    def vlc_playback(self, my_text):
        if self.ACTIVE == False:
            return

        else:

#            print("Sending to GTTS")
            tts = gTTS(text = my_text, lang = LANGUAGE, debug = self.DEBUG)
        
#            print("Text Processed")
            tts.write_to_fp()
        
#            print("ReceivED INFO PLAYING INFO FROM %s" % tts.latest_url )
            media = self.instance.media_new(tts.latest_url)
        
#            print("Opening the media")
            self.player.set_media(media)
        
            self.player.play()
            return


    def processtime(self):
        date_time = time.ctime()
        cur_time = date_time[-13:-1].replace(":"," ")
        date = date_time[0:-13]
        return (cur_time,date)

    def sys_process(self,my_string):
        process_dict = {
                        'blue blue red blue' : (os._exit,0),
                        'red red blue red' : (lambda x :subprocess.call(['sudo','reboot']),0),
                        'stop listening'  : (lambda x: vars().update({'ACTIVE' : False}), ''),
                        'start listening' : (lambda x: vars().update({'ACTIVE':True}), '')
                             
        }
        try:
            prog_tup = process_dict[my_string]
            prog_tup[0](prog_tup[1])

        except:
            return

    def task_thread(self,timing = 60):
        while True:
            time.sleep(.5)
            r = requests.get(REM_ENDPOINT)
            print(r)
            if len(r.content) > 0:
                self.vlc_playback(str(r.content))
            else:
                pass
Exemple #17
0
class Player(object):

    def __init__(self, email, password, device_id):
        self.api = Mobileclient()
        self.vlc = Instance()
        self.loaded_tracks = []
        self.playing = False
        self.thread_running = False
        
        self.api.login(email, password, device_id)
        if os.path.isfile("songs.json"):
            # Load from file
            print("Found songs data.")
            with open('songs.json') as input_file:
                self.song_library = json.load(input_file)
        else:
            self.song_library = self.api.get_all_songs()
            # Save to file
            with open('songs.json', 'w') as output_file:
                json.dump(self.song_library, output_file)    
        
    def load_playlist(self, name):
        name = name.strip().lower()
        print("Looking for...", name)
        if os.path.isfile("playlists.json"):
            # Load from file
            print("Found playlist data.")
            with open('playlists.json') as input_file:
                self.playlists = json.load(input_file)
        else:
            self.playlists = self.api.get_all_user_playlist_contents()
            # Save to file
            with open('playlists.json', 'w') as output_file:
                json.dump(self.playlists, output_file)
            
        self.loaded_tracks = []
        for playlist_dict in self.playlists:
            playlist_name = playlist_dict['name'].strip().lower()
            if (playlist_name == name) or (name in playlist_name):
                print("Found match...", playlist_dict['name'])
                for track_dict in playlist_dict['tracks']:
                    self.loaded_tracks.append(track_dict)
                return playlist_dict['name']
            else:
                print("Found...", playlist_dict['name'])
        return None
 
    def end_callback(self, event, track_index):
        if track_index < len(self.loaded_tracks):
            self.play_song(self.loaded_tracks[track_index])
            event_manager = self.player.event_manager()
            event_manager.event_attach(EventType.MediaPlayerEndReached, self.end_callback, track_index + 1)
            self.playing = True
        else:
            self.playing = False

    def start_playlist(self):
        if len(self.loaded_tracks) > 0:
            self.play_song(self.loaded_tracks[0])
        
            if len(self.loaded_tracks) > 1:
                event_manager = self.player.event_manager()
                event_manager.event_attach(EventType.MediaPlayerEndReached, self.end_callback, 1)
  
    def play_song(self, song_dict):
        stream_url = self.api.get_stream_url(song_dict['trackId'])
        self.player = self.vlc.media_player_new()
        media = self.vlc.media_new(stream_url)
        self.player.set_media(media)
        self.player.play()

        song_string = ""
        if (song_dict['source'] == '2'):
            song_string = self.get_song_details(song_dict)
        else:
            song_string = self.get_local_song_details(song_dict['trackId'])

        print("Playing...",song_string)
        
        if enable_display:
            scrollphat.clear()
            scrollphat.write_string(" "*5+song_string)

            if not self.thread_running:
                thread = Thread(target=self.scroll_string)
                thread.start()

        self.playing = True

    def scroll_string(self):
        self.thread_running = True
        while self.thread_running:
            scrollphat.scroll()
            time.sleep(0.1)

    def stop(self):
        if self.player != None:
            self.player.stop()
        if enable_display:
            scrollphat.clear()
        self.thread_running = False
        self.playing = False

    def get_local_song_details(self, track_id):
        for song_dict in self.song_library:
            if track_id == song_dict['id']:
                return song_dict['albumArtist']+" - "+song_dict['title']

    def get_song_details(self, song_dict):
        return song_dict['track']['albumArtist']+" - "+song_dict['track']['title']
Exemple #18
0
class YoutubePLR:
    def __init__(self):
        self.Player = Instance('--loop')

    def Vplayer(self, url):
        url = str(url)
        video = pafy.new(url)
        messagebox.showinfo(
            "Notice", " Please Wait....  Seeking video may take some time")
        best = video.getbest()
        self.media_list = self.Player.media_list_new()
        self.media_player = self.Player.media_list_player_new()
        self.media = self.Player.media_new(best.url)
        self.media_list.add_media(self.media)
        self.media_player.set_media_list(self.media_list)
        self.media_player.play()
        time.sleep(15)

    def stopVideo(self):
        #media.stop()
        print("Stoping")
        self.media_player.stop()
        #sys.exit()

    def callSearch(self):
        messagebox.showinfo("Notice",
                            " Please Wait....  Searching may take some time.")
        videoName = str(self.video_Name.get())
        print(videoName)
        if videoName is not None:
            videosSearch = VideosSearch(str(videoName), limit=5)

            for i in range(5):
                self.titleList.append(
                    str(videosSearch.result()['result'][i]['title'][0:45]))
                self.linkList.append(
                    videosSearch.result()['result'][i]['link'])
            for i in range(5):
                print(self.titleList[i], "\t\t", self.linkList[i])
                #print(videosSearch.result()['result'][i]['title'][0:45])

            time.sleep(5)
            self.WidgetResult()
        else:
            print("Null Search")

    def Browse(self):
        download_Directory = filedialog.askdirectory(
            initialdir=pathlib.Path.cwd())
        self.download_Path.set(download_Directory)

    def Download(self, url):
        Youtube_link = str(url)
        print(Youtube_link)
        download_Folder = self.download_Path.get()
        print(download_Folder)
        if download_Folder == None or download_Folder == "":
            messagebox.showwarning("Choose Location",
                                   "Choose a valid location in browse option")
            return
        try:
            getVideo = pafy.new(Youtube_link)
            vidBest = getVideo.getbest()
            print(" Downloading -----", vidBest.resolution, vidBest.extension,
                  " .....Please Wait ")
            messagebox.showinfo(
                "Notice", " Please Wait....  Downloading may take some time")
            vidBest.download(download_Folder)
            messagebox.showinfo("Successfully",
                                "Downloaded and Saved in\n" + download_Folder)
        except:
            print("Connection Error")

    def Widgets(self):
        Label(self.root,
              text="Youtube Player and Downloader",
              font=("Gill Sans Ultra Bold Condensed", 30),
              bg="#000000",
              fg="#f9540b").grid(row=1, columnspan=3, padx=18)

        link_label = Label(self.root,
                           text="Search Video",
                           bg="#E8D579",
                           width=20)
        link_label.grid(row=3, column=0, pady=10, padx=10)

        linkText = Entry(self.root, width=40, textvariable=self.video_Name)
        linkText.insert(END, 'attention')
        linkText.grid(row=3, column=1, pady=10, padx=5)

        Search_B = Button(self.root,
                          text="Search",
                          command=self.callSearch,
                          width=15,
                          bg="#05E8E0")
        Search_B.grid(row=3, column=2, pady=10, padx=5)

    def WidgetResult(self):
        self.root.geometry("690x360")
        colrLab = "#cccccc"
        colrBut = "#fd9c35"
        #command= lambda: self.Vplayer(self.linkList[0])
        destination_label = Label(self.root,
                                  text="Destination",
                                  bg="#E8D579",
                                  width=20)
        destination_label.grid(row=4, column=0, pady=10, padx=10)

        destiText = Entry(self.root, width=40, textvariable=self.download_Path)
        destiText.insert(END, '')
        destiText.grid(row=4, column=1, pady=10, padx=5)

        browse_B = Button(self.root,
                          text="Browse",
                          command=self.Browse,
                          width=15,
                          bg="#05E8E0")
        browse_B.grid(row=4, column=2, pady=10, padx=5)

        # Search list

        resultLabel_1 = Label(self.root,
                              text=self.titleList[0],
                              bg=colrLab,
                              width=50)  #1
        resultLabel_1.grid(row=5, columnspan=2, pady=5, padx=5)

        Search_B_1 = Button(self.root,
                            text="Play",
                            command=lambda: self.Vplayer(self.linkList[0]),
                            width=10,
                            bg=colrBut)
        Search_B_1.grid(row=5, column=2, pady=1, padx=1)

        Download_B_1 = Button(self.root,
                              text="Download",
                              command=lambda: self.Download(self.linkList[0]),
                              width=10,
                              bg="#a2cf6e",
                              bd=1)
        Download_B_1.grid(row=5, column=3, pady=3, padx=3)

        resultLabel_2 = Label(self.root,
                              text=self.titleList[1],
                              bg=colrLab,
                              width=50)  #2
        resultLabel_2.grid(row=6, columnspan=2, pady=5, padx=5)

        Search_B_2 = Button(self.root,
                            text="Play",
                            command=lambda: self.Vplayer(self.linkList[1]),
                            width=10,
                            bg=colrBut)
        Search_B_2.grid(row=6, column=2, pady=1, padx=1)

        Download_B_2 = Button(self.root,
                              text="Download",
                              command=lambda: self.Download(self.linkList[1]),
                              width=10,
                              bg="#a2cf6e",
                              bd=1)
        Download_B_2.grid(row=6, column=3, pady=3, padx=3)

        resultLabel_3 = Label(self.root,
                              text=self.titleList[2],
                              bg=colrLab,
                              width=50)  #3
        resultLabel_3.grid(row=7, columnspan=2, pady=5, padx=5)

        Search_B_3 = Button(self.root,
                            text="Play",
                            command=lambda: self.Vplayer(self.linkList[2]),
                            width=10,
                            bg=colrBut)
        Search_B_3.grid(row=7, column=2, pady=1, padx=1)

        Download_B_3 = Button(self.root,
                              text="Download",
                              command=lambda: self.Download(self.linkList[2]),
                              width=10,
                              bg="#a2cf6e",
                              bd=1)
        Download_B_3.grid(row=7, column=3, pady=3, padx=3)

        resultLabel_4 = Label(self.root,
                              text=self.titleList[3],
                              bg=colrLab,
                              width=50)  #4
        resultLabel_4.grid(row=8, columnspan=2, pady=5, padx=5)

        Search_B_4 = Button(self.root,
                            text="Play",
                            command=lambda: self.Vplayer(self.linkList[3]),
                            width=10,
                            bg=colrBut)
        Search_B_4.grid(row=8, column=2, pady=1, padx=1)

        Download_B_4 = Button(self.root,
                              text="Download",
                              command=lambda: self.Download(self.linkList[3]),
                              width=10,
                              bg="#a2cf6e",
                              bd=1)
        Download_B_4.grid(row=8, column=3, pady=3, padx=3)

        resultLabel_5 = Label(self.root,
                              text=self.titleList[4],
                              bg=colrLab,
                              width=50)  #5
        resultLabel_5.grid(row=9, columnspan=2, pady=5, padx=5)

        Search_B_5 = Button(self.root,
                            text="Play",
                            command=lambda: self.Vplayer(self.linkList[4]),
                            width=10,
                            bg=colrBut)
        Search_B_5.grid(row=9, column=2, pady=1, padx=1)

        Download_B_5 = Button(self.root,
                              text="Download",
                              command=lambda: self.Download(self.linkList[4]),
                              width=10,
                              bg="#a2cf6e",
                              bd=1)
        Download_B_5.grid(row=9, column=3, pady=3, padx=3)

        Stop_B = Button(self.root,
                        text="Stop Video",
                        command=self.stopVideo,
                        width=20,
                        bg="#a2cf6e")
        Stop_B.grid(row=10, column=1, pady=8, padx=3)

        #Download_B=Button(self.root,text="Download",command=Download,width=20,bg="#a2cf6e",bd=1)
        #Download_B.grid(row=9,column=1,pady=3,padx=3)

    def Start(self):
        self.root = Tk()
        self.root.geometry("600x130")
        #self.root.resizable(0,0)
        self.root.title("Youtube Video Downloader")
        self.root.config(background="#000000")
        self.video_Name = StringVar()
        self.download_Path = StringVar()
        self.titleList = []
        self.linkList = []

        self.Widgets()
        self.root.mainloop()
Exemple #19
0
class Parlante:
    def __init__(self, numero, mqtt):
        self.path_sonidos = 'sonidos/'
        self.sonidos = [""]

        self.numero = numero

        self.mqtt = mqtt
        self.mqtt.client.on_message = self.on_message
        self.mqtt.client.subscribe("parlante" + str(numero), qos=1)

        self.instance = Instance()
        self.mediaplayer = None
        self.media = None

        self.modo = None
        self.sonido = None

    def on_message(self, client, userdata, msg):
        # hay un cambio
        print(str(msg.payload))
        comando, modo, volumen, sonido = str(msg.payload).split(':')
        self.analizar_mensaje(comando, modo, sonido, volumen)

    def cambiar_era(self):
        self.play("Cambio.mp3", 30)
        time.sleep(3)
        self.stop()
        self.play(self.sonido, self.volumen, loop=True)

    def analizar_mensaje(self, comando, modo, sonido, volumen):
        if comando:
            self.comando = comando
            self.modo = modo
            self.sonido = sonido
            self.volumen = volumen
            if comando == 'set_volume':
                self.set_vol(volumen)
            elif comando == 'cambio_era':
                self.cambiar_era()
            elif comando == 'reset':
                self.stop()
                self.__init__(self.numero, self.mqtt)
                self.estado_inicial()
            elif comando == 'loop' and modo == 'inicial':
                self.stop()
                self.__init__(self.numero, self.mqtt)
                self.estado_inicial()
            elif comando == 'stop':
                self.stop()
            elif comando == 'loop':
                self.play(self.sonido, self.volumen, loop=True)

    def set_vol(self, vol):
        if self.mediaplayer:
            #self.vlc.audio_set_volume(int(vol))
            self.mediaplayer.audio_set_volume(50)

    def stop(self):
        if self.mediaplayer:
            self.mediaplayer.stop()

    def estado_inicial(self):
        self.play("Glitch.mp3", 100, loop=True)

    def play(self, sonido, volumen, loop=False):  # HACER LOOP
        if self.mediaplayer:
            self.mediaplayer.stop()
        #self.vlc = vlc.MediaPlayer(self.path_sonidos+sonido)
        if loop:
            self.instance = Instance('--input-repeat=999999')
        else:
            self.instance = Instance()
        self.mediaplayer = self.instance.media_player_new()
        self.media = self.instance.media_new(self.path_sonidos + sonido)
        self.mediaplayer.set_media(self.media)
        self.set_vol(volumen)
        self.mediaplayer.play()
Exemple #20
0
class Player(Tk.Frame):
    """The main window has to deal with events.
    """
    def __init__(self, parent, title=None):
        Tk.Frame.__init__(self, parent)
        self.Player = Instance('--loop')
        self.parent = parent

        #before new update

        #       q1="""SELECT `episode_table`.`episode_num`,
        #   `episode_table`.`episode_time`,
        #   `episode_table`.`episode_season`
        #FROM `personal_use`.`episode_table`;"""
        #        results = read_query(connection, q1)

        #       self.episode_num=results[0][0]-1  ##subracting 1 to match array position of real episode
        #       self.episode_season=results[0][2]
        #       self.episode_time=results[0][1]

        self.first_entrence = 0
        self.label_arr = []
        self.running = 0
        self.dirname = ""
        self.videos = []
        self.video_len = 0

        if title == None:
            title = "tk_vlc"
        self.parent.title(title)

        # Menu Bar
        #   File Menu
        menubar = Tk.Menu(self.parent)
        self.parent.config(menu=menubar)

        fileMenu = Tk.Menu(menubar)
        fileMenu.add_command(label="Open", underline=0, command=self.OnOpen)
        fileMenu.add_command(label="Exit", underline=1, command=self._quit)
        menubar.add_cascade(label="File", menu=fileMenu)

        # The second panel holds controls
        self.player = None
        self.videopanel = ttk.Frame(self.parent)
        self.canvas = Tk.Canvas(self.videopanel).pack(fill=Tk.BOTH, expand=1)
        self.videopanel.pack(fill=Tk.BOTH, expand=1)

        ctrlpanel = ttk.Frame(self.parent)
        pause = ttk.Button(ctrlpanel, text="Pause", command=self.OnPause)
        play = ttk.Button(ctrlpanel, text="Play", command=self.OnPlay)
        stop = ttk.Button(ctrlpanel, text="Stop", command=self.OnStop)
        next = ttk.Button(ctrlpanel, text="Next", command=self.OnNext)
        previous = ttk.Button(ctrlpanel,
                              text="Previous",
                              command=self.OnPrevious)
        volume = ttk.Button(ctrlpanel, text="Volume", command=self.OnSetVolume)
        pause.pack(side=Tk.LEFT)
        play.pack(side=Tk.LEFT)
        stop.pack(side=Tk.LEFT)
        next.pack(side=Tk.LEFT)
        previous.pack(side=Tk.LEFT)
        volume.pack(side=Tk.LEFT)
        self.volume_var = Tk.IntVar()
        self.volslider = Tk.Scale(ctrlpanel,
                                  variable=self.volume_var,
                                  command=self.volume_sel,
                                  from_=0,
                                  to=100,
                                  orient=Tk.HORIZONTAL,
                                  length=100)
        self.volslider.pack(side=Tk.LEFT)
        ctrlpanel.pack(side=Tk.BOTTOM)

        ctrlpanel2 = ttk.Frame(self.parent)
        self.scale_var = Tk.DoubleVar()
        self.timeslider_last_val = ""
        self.timeslider = Tk.Scale(ctrlpanel2,
                                   variable=self.scale_var,
                                   command=self.scale_sel,
                                   from_=0,
                                   to=1000,
                                   orient=Tk.HORIZONTAL,
                                   length=500)
        self.timeslider.pack(side=Tk.BOTTOM, fill=Tk.X, expand=1)
        self.timeslider_last_update = time.time()
        ctrlpanel2.pack(side=Tk.BOTTOM, fill=Tk.X)

        # VLC player controls
        self.Instance = vlc.Instance()
        self.player = self.Instance.media_player_new()

        self.timer = ttkTimer(self.OnTimer, 1.0)
        self.timer.start()

        self.parent.update()

    def printSomething(self, txt):
        # if you want the button to disappear:
        # button.destroy() or button.pack_forget()
        # 0 is unnecessary

        if len(self.label_arr) > 0:
            self.label_arr[-1].destroy()
        label = Tk.Label(root, text=txt)
        # this creates x as a new label to the GUI
        label.pack()
        self.label_arr.append(label)

    def OnNext(self):

        if self.episode_num < len(self.videos) - 1:  ##in season
            self.episode_num += 1
            #    q1="""TRUNCATE `personal_use`.`episode_table`;"""
            #    execute_query(connection, q1)
            #    q1="""INSERT INTO `personal_use`.`episode_table`
            #            (`episode_num`,
            #            `episode_time`,
            #            `episode_season`)
            #                VALUES
            #                ("""+str(self.episode_num+1)+""","""+str(self.episode_time)+""","""+str(self.episode_season)+""");"""
            #    execute_query(connection,q1)
            q1 = """UPDATE `personal_use`.`episode_table`
                SET
                `episode_num`= """ + str(self.episode_num + 1) + """,
                `episode_time` = """ + str(self.episode_time) + """,
                `episode_season`=""" + str(self.episode_season) + """
                WHERE  `show_name`='""" + str(self.show_name) + """';
                """
            execute_query(connection, q1)

            self.Create(self.dirname, self.videos[self.episode_num])
            self.OnPlay()
        else:  ##start new season
            self.episode_season += 1
            self.episode_num = 1
            #q1 = """TRUNCATE `personal_use`.`episode_table`;"""
            #execute_query(connection, q1)
            #q1 = """INSERT INTO `personal_use`.`episode_table`
            #                    (`episode_num`,
            #                    `episode_time`,
            #                    `episode_season`)
            #                        VALUES
            #                        (""" + str(self.episode_num) + """,""" + str(self.episode_time) + """,""" + str(
            #    self.episode_season) + """);"""
            #execute_query(connection, q1)

            q1 = """UPDATE `personal_use`.`episode_table`
                           SET
                           `episode_num`= """ + str(self.episode_num) + """,
                           `episode_time` = """ + str(self.episode_time) + """,
                           `episode_season`=""" + str(
                self.episode_season) + """
                           WHERE  `show_name`='""" + str(
                    self.show_name) + """';
                           """
            execute_query(connection, q1)

            self.episode_num -= 1  ##so it will match the array
            self.OnOpen()

    def OnPrevious(self):

        if self.episode_num > 0:  ##in season
            self.episode_num -= 1
            #q1 = """TRUNCATE `personal_use`.`episode_table`;"""
            #execute_query(connection, q1)
            #q1 = """INSERT INTO `personal_use`.`episode_table`
            #                    (`episode_num`,
            #                    `episode_time`,
            #                    `episode_season`)
            #                        VALUES
            #                        (""" + str(self.episode_num+1) + """,""" + str(self.episode_time) + """,""" + str(
            #    self.episode_season) + """);"""
            #execute_query(connection, q1)

            q1 = """UPDATE `personal_use`.`episode_table`
                                       SET
                                       `episode_num`= """ + str(
                self.episode_num + 1) + """,
                                       `episode_time` = """ + str(
                    self.episode_time) + """,
                                       `episode_season`=""" + str(
                        self.episode_season) + """
                                       WHERE  `show_name`='""" + str(
                            self.show_name) + """';
                                       """
            execute_query(connection, q1)

            self.Create(self.dirname, self.videos[self.episode_num])
            self.OnPlay()
        else:  ##back to previous season
            self.episode_season -= 1

            #self.dirname = r"C:\Users\tonyh\OneDrive\Desktop\shows and movies\shows\that 70s show\season"
            #self.dirname += str(self.episode_season)

            self.dirname = r"C:\Users\tonyh\OneDrive\Desktop\shows and movies\shows"
            self.dirname += "\\"
            self.dirname += self.show_name
            self.dirname += "\\"
            self.dirname += "season"
            self.dirname += str(self.episode_season)

            self.mediaList = self.Player.media_list_new()
            self.videos = os.listdir(self.dirname)

            self.episode_num = len(self.videos)

            #q1 = """TRUNCATE `personal_use`.`episode_table`;"""
            #execute_query(connection, q1)
            #q1 = """INSERT INTO `personal_use`.`episode_table`
            #                                (`episode_num`,
            #                                `episode_time`,
            #                                `episode_season`)
            #                                    VALUES
            #                                    (""" + str(self.episode_num) + """,""" + str(
            #    self.episode_time) + """,""" + str(
            #    self.episode_season) + """);"""
            #execute_query(connection, q1)

            q1 = """UPDATE `personal_use`.`episode_table`
                                                   SET
                                                   `episode_num`= """ + str(
                self.episode_num) + """,
                                                   `episode_time` = """ + str(
                    self.episode_time) + """,
                                                   `episode_season`=""" + str(
                        self.episode_season) + """
                                                   WHERE  `show_name`='""" + str(
                            self.show_name) + """';
                                                   """
            execute_query(connection, q1)

            self.episode_num -= 1  ##so it will match the array
            self.OnOpen()

    def OnExit(self, evt):
        """Closes the window.
        """
        self.Close()

    def OnOpen(self):
        """Pop up a new dialow window to choose a file, then play the selected file.
        """
        # if a file is already running, then stop it.
        self.OnStop()

        # Create a file dialog opened in the current home directory, where
        # you can display all kind of files, having as title "Choose a file".
        #p = pathlib.Path(os.path.expanduser("~"))
        p = pathlib.Path(
            os.path.expanduser(
                r"C:\Users\tonyh\OneDrive\Desktop\shows and movies\shows\show names"
            ))
        fullname = askopenfilename(initialdir=p,
                                   title="choose your file",
                                   filetypes=(("all files", "*.*"),
                                              ("mp4 files", "*.mp4")))
        #if os.path.isfile(fullname):
        #    print(fullname)
        #    splt = os.path.split(fullname)

        #dirname = os.path.dirname(fullname)

        #new addition
        filename = os.path.basename(fullname)
        filename = filename[:-4]  ##deletes the .txt from the name

        print(filename)
        #self.dirname=r"C:\Users\tonyh\OneDrive\Desktop\shows and movies\shows\that 70s show\season1"

        ##defining the properties of the show:

        q1 = """SELECT `episode_table`.`episode_num`,
            `episode_table`.`episode_time`,
            `episode_table`.`episode_season`
    
            FROM `personal_use`.`episode_table`

            WHERE `episode_table`.`show_name`='""" + filename + """'"""
        results = read_query(connection, q1)
        self.episode_num = results[0][
            0] - 1  ##subracting 1 to match array position of real episode
        self.episode_season = results[0][2]
        self.episode_time = results[0][1]
        self.show_name = filename

        ##new addition
        self.dirname = r"C:\Users\tonyh\OneDrive\Desktop\shows and movies\shows"
        self.dirname += "\\"
        self.dirname += filename
        self.dirname += "\\"
        self.dirname += "season"
        self.dirname += str(self.episode_season)

        ##before updating

        #self.dirname=r"C:\Users\tonyh\OneDrive\Desktop\shows and movies\shows\that 70s show\season"
        #self.dirname+=str(self.episode_season)

        ##tony
        ##creating the array of episodes
        self.mediaList = self.Player.media_list_new()
        self.videos = os.listdir(self.dirname)

        for v in self.videos:
            self.mediaList.add_media(
                self.Player.media_new(os.path.join(self.dirname, v)))
            self.listPlayer = self.Player.media_list_player_new()
            self.listPlayer.set_media_list(self.mediaList)

        self.Create(self.dirname, self.videos[self.episode_num])
        # Creation
        #self.Media = self.Instance.media_new(str(os.path.join(dirname, filename)))
        #self.player.set_media(self.Media)
        # Report the title of the file chosen
        # title = self.player.get_title()
        #  if an error was encountred while retriving the title, then use
        #  filename
        # if title == -1:
        #    title = filename
        # self.SetTitle("%s - tkVLCplayer" % title)

        # set the window id where to render VLC's video output

        ##tony: you turned of this so it opens a seperate window

        #if platform.system() == 'Windows':
        #    self.player.set_hwnd(self.GetHandle())
        #else:
        #    self.player.set_xwindow(self.GetHandle())  # this line messes up windows
        # FIXME: this should be made cross-platform

        self.OnPlay()

        # set the volume slider to the current volume
        # self.volslider.SetValue(self.player.audio_get_volume() / 2)
        self.volslider.set(self.player.audio_get_volume())

    def Create(self, dirname, filename):

        if self.first_entrence == 0:  ##if first time then start from the time you stopped
            self.Media = self.Instance.media_new(
                str(os.path.join(dirname, filename)))

            self.Media.add_option('start-time=' + str(self.episode_time) + '')
            self.player.set_media(self.Media)
            self.first_entrence += 1

        else:
            self.Media = self.Instance.media_new(
                str(os.path.join(dirname, filename)))
            self.player.set_media(self.Media)

        self.video_len = VideoFileClip(str(os.path.join(dirname, filename)))
        self.video_len = self.video_len.duration
        self.running = 1
        self.printSomething(filename)

    def OnPlay(self):
        """Toggle the status to Play/Pause.
        If no file is loaded, open the dialog window.
        """
        # check if there is a file to play, otherwise open a
        # Tk.FileDialog to select a file
        if not self.player.get_media():
            self.OnOpen()

        else:
            # Try to launch the media, if this fails display an error message
            if self.player.play() == -1:
                self.errorDialog("Unable to play.")

    def GetHandle(self):
        return self.videopanel.winfo_id()

    # def OnPause(self, evt):
    def OnPause(self):
        """Pause the player.
        """
        self.player.pause()

    def OnStop(self):
        """Stop the player.
        """
        self.player.stop()
        # reset the time slider
        if self.first_entrence != 0:
            self.timeslider.set(0)

    def OnTimer(self):
        """Update the time slider according to the current movie time.
        """

        if self.player == None:
            return
        # since the self.player.get_length can change while playing,
        # re-set the timeslider to the correct range.
        length = self.player.get_length()
        dbl = length * 0.001
        self.timeslider.config(to=dbl)

        # update the time on the slider
        tyme = self.player.get_time()
        if tyme == -1:
            tyme = 0
        dbl = tyme * 0.001

        if self.first_entrence != 0:  ##important for starting from saved time
            self.episode_time = dbl
        self.timeslider_last_val = ("%.0f" % dbl) + ".0"

        # don't want to programatically change slider while user is messing with it.
        # wait 2 seconds after user lets go of slider
        if time.time() > (self.timeslider_last_update + 2.0):
            self.timeslider.set(dbl)

        if self.running == 1:
            if dbl > self.video_len - 1:
                time.sleep(5)
                if dbl > self.video_len - 1:
                    self.running = 0
                    self.player.set_time(0)
                    self.OnNext()

    def scale_sel(self, evt):
        if self.player == None:
            return
        nval = self.scale_var.get()
        sval = str(nval)
        if self.timeslider_last_val != sval:
            # this is a hack. The timer updates the time slider.
            # This change causes this rtn (the 'slider has changed' rtn) to be invoked.
            # I can't tell the difference between when the user has manually moved the slider and when
            # the timer changed the slider. But when the user moves the slider tkinter only notifies
            # this rtn about once per second and when the slider has quit moving.
            # Also, the tkinter notification value has no fractional seconds.
            # The timer update rtn saves off the last update value (rounded to integer seconds) in timeslider_last_val
            # if the notification time (sval) is the same as the last saved time timeslider_last_val then
            # we know that this notification is due to the timer changing the slider.
            # otherwise the notification is due to the user changing the slider.
            # if the user is changing the slider then I have the timer routine wait for at least
            # 2 seconds before it starts updating the slider again (so the timer doesn't start fighting with the
            # user)
            # selection = "Value, last = " + sval + " " + str(self.timeslider_last_val)
            # print("selection= ", selection)
            self.timeslider_last_update = time.time()
            mval = "%.0f" % (nval * 1000)
            self.player.set_time(int(mval))  # expects milliseconds

    def volume_sel(self, evt):
        if self.player == None:
            return
        volume = self.volume_var.get()
        if volume > 100:
            volume = 100
        if self.player.audio_set_volume(volume) == -1:
            self.errorDialog("Failed to set volume")

    def OnToggleVolume(self, evt):
        """Mute/Unmute according to the audio button.
        """
        is_mute = self.player.audio_get_mute()

        self.player.audio_set_mute(not is_mute)
        # update the volume slider;
        # since vlc volume range is in [0, 200],
        # and our volume slider has range [0, 100], just divide by 2.
        self.volume_var.set(self.player.audio_get_volume())

    def OnSetVolume(self):
        """Set the volume according to the volume sider.
        """
        volume = self.volume_var.get()
        print("volume= ", volume)
        # volume = self.volslider.get() * 2
        # vlc.MediaPlayer.audio_set_volume returns 0 if success, -1 otherwise
        if volume > 100:
            volume = 100
        if self.player.audio_set_volume(volume) == -1:
            self.errorDialog("Failed to set volume")

    def errorDialog(self, errormessage):
        """Display a simple error dialog.
        """
        edialog = Tk.tkMessageBox.showerror(self, 'Error', errormessage)

    def _quit(self):
        q1 = """UPDATE `personal_use`.`episode_table` SET `episode_num` = """ + str(
            self.episode_num + 1) + """,`episode_time` = '""" + str(
                self.episode_time) + """',`episode_season` ='""" + str(
                    self.episode_season) + """'   WHERE
        `show_name` = '""" + str(self.show_name) + """';"""

        execute_query(connection, q1)
        print("_quit: bye")
        root = Tk_get_root()
        root.quit()  # stops mainloop
        root.destroy()  # this is necessary on Windows to prevent
        # Fatal Python Error: PyEval_RestoreThread: NULL tstate
        os._exit(1)
class MyMediaPlayer(object):
    """
        Simple audio/video player based on VLC player.
    """

    def __init__(self):
        self._vlc_instance = Instance()
        self._volume = 100
        self._song_list = []
        self._song_finished_func = None
        self._song_started_func = None
        self._playlist_finished_func = None
        self._current_index = -1

    def subscribe_song_finished(self, func, *args, **kwargs):
        """
            Subscriber for when player finishes a song
        """
        self._song_finished_func = functools.partial(func, *args, **kwargs)

    def subscribe_playlist_finished(self, func, *args, **kwargs):
        """
            Subscriber for when player finishes all songs in existing playlist
        """
        self._playlist_finished_func = functools.partial(func, *args, **kwargs)

    def subscribe_song_started(self, func, *args, **kwargs):
        """
            Subscriber for when player finishes a song
        """
        self._song_started_func = functools.partial(func, *args, **kwargs)

    def _finished_song_event(self, event):
        """
            Event for when a player finishes a song.
        """
        config.logging.debug(f'Event from VLC player: {event}')
        self._play_next()
        if self._song_finished_func:
            self._song_finished_func()

    def _finished_playlist_event(self):
        """
            Event for when a player finishes a song.
        """
        config.logging.debug(f'Finished playlist event')
        if self._playlist_finished_func:
            self._playlist_finished_func()

    def _started_song_event(self, event):
        """
            Event for when a player starts a song.
        """
        config.logging.debug(f'Event from VLC player: {event}')
        if self._song_started_func:
            self._song_started_func()

    @check_song_list
    def play(self, *, songs):
        """
            Plays the given song list (a list of Song objects).
        """
        if songs:
            self._song_list.extend(songs)

        # stop any current play
        self.stop()
        # start playing the next song (self._current_index points to that)
        self._play_next()

    @check_song_list
    def add_to_playlist(self, *, songs):
        """
            Appends a song or a list of songs to the existing playlist.
        """
        if songs:
            self._song_list.extend(songs)

    @check_song_list
    def delete_from_playlist(self, *, songs):
        """
            Deletes a song or a list of songs from the existing playlist.
        """
        for song in songs:
            for song_player in self._song_list:
                # TODO: implement a proper check (do not use ids because that's only for favorite songs)
                if song == song_player:
                    self._song_list.remove(song_player)
                    break
        # TODO: remove from the list. Check the id of the song to identify it

    @check_media
    def stop(self):
        """
            Stops the player.
        """
        self._player.stop()

    @check_media
    def pause(self):
        """
            Pauses and resumes the music.
        """
        self._player.pause()

    @check_media
    def get_time(self):
        """
            Gets the elapsed time of the current song.
        """
        time = self._player.get_time()
        time_str = str(int(time / 60000)) + ':' + format(int((time % 60000) / 1000), '02d')
        return time_str

    @check_media
    def set_volume(self, volume):
        """
            Sets the volume of the player.
        """
        if isinstance(volume, str):
            volume = float(volume)
        if isinstance(volume, (float, int)):
            volume = int(round(volume))
        self._volume = volume
        self._player.audio_set_volume(volume)

    @check_media
    def is_playing(self):
        """
            Checks if any media is playing.
        """
        return self._player.get_state() == State.Playing

    @check_media
    def get_length(self):
        """
            Gets the length of the current media playing.
        """
        return self._player.get_duration()

    @check_media
    def get_current_song(self):
        """
            Gets the info from the mp3 playing currently
        """
        song = None
        if self._current_index < len(self._song_list):
            song = self._song_list[self._current_index]
        return song

    def _play_next(self):
        """
            Plays the next song in the list
        """
        self._current_index += 1
        if len(self._song_list) > self._current_index:
            self._media = self._vlc_instance.media_new(self._song_list[self._current_index].abs_path)
            self._player = self._vlc_instance.media_player_new()
            self._player.set_media(self._media)
            self._player.event_manager().event_attach(EventType.MediaPlayerEndReached, self._finished_song_event)
            self._player.event_manager().event_attach(EventType.MediaPlayerPlaying, self._started_song_event)
            self._player.audio_set_volume(self._volume)
            self._player.play()
        elif len(self._song_list) == self._current_index:
            self._finished_playlist_event()
            config.logger.debug('Finished playing the list of songs')
        else:
            config.logger.error(
                f'Current playing index is {self._current_index} and the length of the list is {len(self._song_list)}')
Exemple #22
0
class PiecesPlayer(QWidget):
    """ main widget of application (used as widget inside PiecesMainWindow) """
    def __init__(self, parent):
        """ standard constructor: set up class variables, ui elements
            and layout """

        # TODO: split current piece info into separate lineedits for title, album name and length
        # TODO: make time changeable by clicking next to the slider (not only
        #       by dragging the slider)
        # TODO: add "about" action to open info dialog in new "help" menu
        # TODO: add option to loop current piece (?)
        # TODO: more documentation
        # TODO: add some "whole piece time remaining" indicator? (complicated)
        # TODO: implement a playlist of pieces that can be edited and enable
        #       going back to the previous piece (also un- and re-shuffling?)
        # TODO: implement debug dialog as menu action (if needed)

        if not isinstance(parent, PiecesMainWindow):
            raise ValueError('Parent widget must be a PiecesMainWindow')

        super(PiecesPlayer, self).__init__(parent=parent)

        # -- declare and setup variables for storing information --
        # various data
        self._set_str = ''  # string of currently loaded directory sets
        self._pieces = {}  # {<piece1>: [<files piece1 consists of>], ...}
        self._playlist = []  # list of keys of self._pieces (determines order)
        self._shuffled = True  # needed for (maybe) reshuffling when looping
        # doc for self._history:
        # key: timestamp ('HH:MM:SS'),
        # value: info_str of piece that started playing at that time
        self._history = {}
        self._status = 'Paused'
        self._current_piece = {'title': '', 'files': [], 'play_next': 0}
        self._default_volume = 60  # in percent from 0 - 100
        self._volume_before_muted = self._default_volume
        # set to true by self.__event_movement_ended and used by self.__update
        self._skip_to_next = False
        # vlc-related variables
        self._vlc_instance = VLCInstance()
        self._vlc_mediaplayer = self._vlc_instance.media_player_new()
        self._vlc_mediaplayer.audio_set_volume(self._default_volume)
        self._vlc_medium = None
        self._vlc_events = self._vlc_mediaplayer.event_manager()

        # -- create and setup ui elements --
        # buttons
        self._btn_play_pause = QPushButton(QIcon(get_icon_path('play')), '')
        self._btn_previous = QPushButton(QIcon(get_icon_path('previous')), '')
        self._btn_next = QPushButton(QIcon(get_icon_path('next')), '')
        self._btn_volume = QPushButton(QIcon(get_icon_path('volume-high')), '')
        self._btn_loop = QPushButton(QIcon(get_icon_path('loop')), '')
        self._btn_loop.setCheckable(True)
        self._btn_play_pause.clicked.connect(self.__action_play_pause)
        self._btn_previous.clicked.connect(self.__action_previous)
        self._btn_next.clicked.connect(self.__action_next)
        self._btn_volume.clicked.connect(self.__action_volume_clicked)
        # labels
        self._lbl_current_piece = QLabel('Current piece:')
        self._lbl_movements = QLabel('Movements:')
        self._lbl_time_played = QLabel('00:00')
        self._lbl_time_left = QLabel('-00:00')
        self._lbl_volume = QLabel('100%')
        # needed so that everything has the same position
        # independent of the number of digits of volume
        self._lbl_volume.setMinimumWidth(55)
        # sliders
        self._slider_time = QSlider(Qt.Horizontal)
        self._slider_volume = QSlider(Qt.Horizontal)
        self._slider_time.sliderReleased.connect(
            self.__event_time_changed_by_user)
        self._slider_volume.valueChanged.connect(self.__event_volume_changed)
        self._slider_time.setRange(0, 100)
        self._slider_volume.setRange(0, 100)
        self._slider_volume.setValue(self._default_volume)
        self._slider_volume.setMinimumWidth(100)
        # other elements
        self._checkbox_loop_playlist = QCheckBox('Loop playlist')
        self._lineedit_current_piece = QLineEdit()
        self._lineedit_current_piece.setReadOnly(True)
        self._lineedit_current_piece.textChanged.connect(
            self.__event_piece_text_changed)
        self._listwidget_movements = QListWidget()
        self._listwidget_movements.itemClicked.connect(
            self.__event_movement_selected)

        # -- create layout and insert ui elements--
        self._layout = QVBoxLayout(self)
        # row 0 (name of current piece)
        self._layout_piece_name = QHBoxLayout()
        self._layout_piece_name.addWidget(self._lbl_current_piece)
        self._layout_piece_name.addWidget(self._lineedit_current_piece)
        self._layout.addLayout(self._layout_piece_name)
        # rows 1 - 5 (movements of current piece)
        self._layout.addWidget(self._lbl_movements)
        self._layout.addWidget(self._listwidget_movements)
        # row 6 (time)
        self._layout_time = QHBoxLayout()
        self._layout_time.addWidget(self._lbl_time_played)
        self._layout_time.addWidget(self._slider_time)
        self._layout_time.addWidget(self._lbl_time_left)
        self._layout.addLayout(self._layout_time)
        # row 7 (buttons and volume)
        self._layout_buttons_and_volume = QHBoxLayout()
        self._layout_buttons_and_volume.addWidget(self._btn_play_pause)
        self._layout_buttons_and_volume.addWidget(self._btn_previous)
        self._layout_buttons_and_volume.addWidget(self._btn_next)
        self._layout_buttons_and_volume.addWidget(self._btn_loop)
        self._layout_buttons_and_volume.addSpacing(40)
        # distance between loop and volume buttons: min. 40, but stretchable
        self._layout_buttons_and_volume.addStretch()
        self._layout_buttons_and_volume.addWidget(self._btn_volume)
        self._layout_buttons_and_volume.addWidget(self._slider_volume)
        self._layout_buttons_and_volume.addWidget(self._lbl_volume)
        self._layout.addLayout(self._layout_buttons_and_volume)

        # -- setup hotkeys --
        self._KEY_CODES_PLAY_PAUSE = [269025044]
        self._KEY_CODES_NEXT = [269025047]
        self._KEY_CODES_PREVIOUS = [269025046]
        self._keyboard_listener = keyboard.Listener(on_press=self.__on_press)
        self._keyboard_listener.start()
        QShortcut(QKeySequence('Space'), self, self.__action_play_pause)

        # -- various setup --
        self._timer = QTimer(self)
        self._timer.timeout.connect(self.__update)
        self._timer.start(100)  # update every 100ms
        self.setMinimumWidth(900)
        self.setMinimumHeight(400)
        # get directory set(s) input and set up self._pieces
        # (exec_ means we'll wait for the user input before continuing)
        DirectorySetChooseDialog(self, self.set_pieces_and_playlist).exec_()
        # skip to next movement / next piece when current one has ended
        self._vlc_events.event_attach(VLCEventType.MediaPlayerEndReached,
                                      self.__event_movement_ended)

    def __action_next(self):
        """ switches to next file in self._current_piece['files']
            or to the next piece, if the current piece has ended """

        reset_pause_after_current = False

        # current movement is last of the current piece
        if self._current_piece['play_next'] == -1:
            if len(self._playlist) == 0:  # reached end of playlist
                if self._btn_loop.isChecked():
                    self._playlist = list(self._pieces.keys())
                    if self._shuffled:
                        shuffle(self._playlist)
                    return

                if self._status == 'Playing':
                    self.__action_play_pause()
                self._current_piece['title'] = ''
                self._current_piece['files'] = []
                self._current_piece['play_next'] = -1
                self._lineedit_current_piece.setText('')
                self.__update_movement_list()
                self.parentWidget().update_status_bar(
                    self._status, 'End of playlist reached.')
                return
            else:
                if self.parentWidget().get_exit_after_current():
                    self.parentWidget().exit()
                if self.parentWidget().get_pause_after_current():
                    self.__action_play_pause()
                    reset_pause_after_current = True
                    # reset of the menu action will be at the end of this
                    # function, or else we won't stay paused

                self._current_piece['title'] = self._playlist.pop(0)
                self._current_piece['files'] = [
                    p[1:-1] for p in self._pieces[self._current_piece['title']]
                ]
                # some pieces only have one movement
                self._current_piece['play_next'] = \
                    1 if len(self._current_piece['files']) > 1 else -1
                self.__update_vlc_medium(0)
                self._lineedit_current_piece.setText(
                    create_info_str(self._current_piece['title'],
                                    self._current_piece['files']))
                self.__update_movement_list()
                self._history[datetime.now().strftime('%H:%M:%S')] = \
                    self._lineedit_current_piece.text()
        else:
            self.__update_vlc_medium(self._current_piece['play_next'])
            # next is last movement
            if self._current_piece['play_next'] == \
               len(self._current_piece['files']) - 1:
                self._current_piece['play_next'] = -1
            else:  # there are at least two movements of current piece left
                self._current_piece['play_next'] += 1
        if self._status == 'Paused' and not reset_pause_after_current:
            self.__action_play_pause()
        elif reset_pause_after_current:
            self.parentWidget().set_pause_after_current(False)
        else:
            self._vlc_mediaplayer.play()
        self.parentWidget().update_status_bar(
            self._status,
            f'{len(self._pieces) - len(self._playlist)}/{len(self._pieces)}')

    def __action_play_pause(self):
        """ (gets called when self._btn_play_pause is clicked)
            toggles playing/pausing music and updates everything as needed """

        # don't do anything now (maybe end of playlist reached?)
        if self._current_piece['title'] == '':
            return

        if self._status == 'Paused':
            if not self._vlc_medium:
                self.__action_next()
            self._vlc_mediaplayer.play()
            self._btn_play_pause.setIcon(QIcon(get_icon_path('pause')))
            self._status = 'Playing'
        else:
            self._vlc_mediaplayer.pause()
            self._btn_play_pause.setIcon(QIcon(get_icon_path('play')))
            self._status = 'Paused'
        self.parentWidget().update_status_bar(
            self._status,
            f'{len(self._pieces) - len(self._playlist)}/{len(self._pieces)}')

    def __action_previous(self):
        """ (called when self._btn_previous ist clicked)
            goes back one movement of the current piece, if possible
            (cannot go back to previous piece) """

        # can't go back to previous piece, but current one has no or one movement
        if len(self._current_piece['files']) <= 1:
            pass
        # currently playing first movement, so nothing to do as well
        elif self._current_piece['play_next'] == 1:
            pass
        else:  # we can go back one movement
            # currently at last movement
            if self._current_piece['play_next'] == -1:
                # set play_next to last movement
                self._current_piece['play_next'] = \
                    len(self._current_piece['files']) - 1
            else:  # currently before last movement
                # set play_next to current movement
                self._current_piece['play_next'] -= 1
            self._vlc_mediaplayer.stop()
            self.__update_vlc_medium(self._current_piece['play_next'] - 1)
            self._vlc_mediaplayer.play()

    def __action_volume_clicked(self):
        """ (called when self._btn_volume is clicked)
            (un)mutes volume """

        if self._slider_volume.value() == 0:  # unmute volume
            self._slider_volume.setValue(self._volume_before_muted)
        else:  # mute volume
            self._volume_before_muted = self._slider_volume.value()
            self._slider_volume.setValue(0)

    def __event_movement_ended(self, event):
        """ (called when self._vlc_media_player emits a MediaPlayerEndReached
            event)
            sets self._skip_to_next to True so the next self.__update call
            will trigger self.__action_next """

        self._skip_to_next = True

    def __event_movement_selected(self):
        """ (called when self._listwidget_movements emits itemClicked)
            skips to the newly selected movement """

        index = self._listwidget_movements.indexFromItem(
            self._listwidget_movements.currentItem()).row()
        # user selected a movement different from the current one
        if index != self.__get_current_movement_index():
            self._current_piece['play_next'] = index
            self.__action_next()

    def __event_piece_text_changed(self):
        """ (called when self._lineedit_current_piece emits textChanged)
            ensures that the user sees the beginning of the text in
            self._lineedit_current_piece (if text is too long, the end will be
            cut off and the user must scroll manually to see it) """

        self._lineedit_current_piece.setCursorPosition(0)

    def __event_volume_changed(self):
        """ (called when value of self._slider_volume changes)
            updates text of self._lbl_volume to new value of self._slider_value
            and sets icon of self._btn_volume to a fitting one """

        volume = self._slider_volume.value()
        self._lbl_volume.setText(f'{volume}%')
        if volume == 0:
            self._btn_volume.setIcon(QIcon(get_icon_path('volume-muted')))
        elif volume < 34:
            self._btn_volume.setIcon(QIcon(get_icon_path('volume-low')))
        elif volume < 67:
            self._btn_volume.setIcon(QIcon(get_icon_path('volume-medium')))
        else:
            self._btn_volume.setIcon(QIcon(get_icon_path('volume-high')))
        self._vlc_mediaplayer.audio_set_volume(volume)

    def __event_time_changed_by_user(self):
        """ (called when user releases self._slider_time)
            synchronizes self._vlc_mediaplayer's position to the new value
            of self._slider_time """

        self._vlc_mediaplayer.set_position(self._slider_time.value() / 100)

    def __get_current_movement_index(self):
        """ returns the index of the current movement in
            self._current_piece['files'] """

        play_next = self._current_piece['play_next']
        if play_next == -1:
            return len(self._current_piece['files']) - 1
        else:
            return play_next - 1

    def __on_press(self, key):
        """ (called by self._keyboard_listener when a key is pressed)
            looks up key code corresponding to key and calls the appropriate
            action function """

        try:  # key is not always of the same type (why would it be?!)
            key_code = key.vk
        except AttributeError:
            key_code = key.value.vk
        if key_code in self._KEY_CODES_PLAY_PAUSE:
            self.__action_play_pause()
        elif key_code in self._KEY_CODES_NEXT:
            self.__action_next()
        elif key_code in self._KEY_CODES_PREVIOUS:
            self.__action_previous()

    def __update_movement_list(self):
        """ removes all items currently in self._listwidget_movements and adds
            everything in self._current_piece['files] """

        # TODO: use ID3 title instead of filename

        while self._listwidget_movements.count() > 0:
            self._listwidget_movements.takeItem(0)
        files = self._current_piece['files']
        if os_name == 'nt':  # windows paths look different than posix paths
            # remove path to file, title number and .mp3 ending
            files = [i[i.rfind('\\') + 3:-4] for i in files]
        else:
            files = [i[i.rfind('/') + 4:-4] for i in files]
        self._listwidget_movements.addItems(files)

    def __update(self):
        """ (periodically called when self._timer emits timeout signal)
            updates various ui elements"""

        # -- select currently playing movement in self._listwidget_movements --
        if self._listwidget_movements.count() > 0:
            self._listwidget_movements.item(
                self.__get_current_movement_index()).setSelected(True)

        # -- update text of self._lbl_time_played and self._lbl_time_left,
        # if necessary --
        if self._vlc_medium:
            try:
                time_played = self._vlc_mediaplayer.get_time()
                medium_duration = self._vlc_medium.get_duration()
                # other values don't make sense (but do occur)
                if (time_played >= 0) and (time_played <= medium_duration):
                    self._lbl_time_played.setText(
                        get_time_str_from_ms(time_played))
                else:
                    self._lbl_time_played.setText(get_time_str_from_ms(0))
                self._lbl_time_left.setText(
                    f'-{get_time_str_from_ms(medium_duration - time_played)}')
            except OSError:  # don't know why that occurs sometimes
                pass

        # -- update value of self._slider_time --
        # don't reset slider to current position if user is dragging it
        if not self._slider_time.isSliderDown():
            try:
                self._slider_time.setValue(
                    self._vlc_mediaplayer.get_position() * 100)
            except OSError:  # don't know why that occurs sometimes
                pass

        if self._skip_to_next:
            self._skip_to_next = False
            self.__action_next()

    def __update_vlc_medium(self, files_index):
        old_medium = self._vlc_medium
        self._vlc_medium = self._vlc_instance.media_new(
            self._current_piece['files'][files_index])
        self._vlc_medium.parse()
        self._vlc_mediaplayer.set_media(self._vlc_medium)
        if old_medium:  # only release if not None
            old_medium.release()

    def get_history(self):
        """ getter function for parent widget """

        return self._history

    def get_set_str(self):
        """ getter function for parent widget """

        return self._set_str if self._set_str != '' \
            else 'No directory set loaded.'

    def set_pieces_and_playlist(self, pieces, playlist, set_str, shuffled):
        """ needed so that DirectorySetChooseDialog can set our self._pieces
            and self._playlist """

        # just to be sure
        if isinstance(pieces, dict) and isinstance(playlist, list):
            self._vlc_mediaplayer.stop()
            self._set_str = set_str
            self._pieces = pieces
            self._playlist = playlist
            self._shuffled = shuffled
            self._current_piece['title'] = self._playlist.pop(0)
            self._current_piece['files'] = [
                p.replace('"', '')
                for p in self._pieces[self._current_piece['title']]
            ]
            self._current_piece['play_next'] = \
                1 if len(self._current_piece['files']) > 1 else -1
            self._lineedit_current_piece.setText(
                create_info_str(self._current_piece['title'],
                                self._current_piece['files']))
            self.__update_movement_list()
            self.__update_vlc_medium(0)
            self._history[datetime.now().strftime('%H:%M:%S')] = \
                self._lineedit_current_piece.text()

    def exit(self):
        """ exits cleanly """

        try:  # don't know why that occurs sometimes
            self._vlc_mediaplayer.stop()
            self._vlc_mediaplayer.release()
            self._vlc_instance.release()
        except OSError:
            pass

        self._keyboard_listener.stop()
Exemple #23
0
    def play(self):
        with open("urllist.txt", "r") as f:
            url = f.readline().strip()
            link = url.split(";")
        if link[0]:
            try:
                self.threadLock.acquire()
                audio = pafy.new(link[0])
                best = audio.getbest()
                playurl = best.url
                vInstance = Instance("--novideo")
                self.player = vInstance.media_player_new()
                media = vInstance.media_new(playurl)
                self.player.set_media(media)

                if audio.duration == "00:00:00":
                    self.update()
                    self.logBrowser.append(
                        "Denied. Tried to play livestream video...")
                    self.threadLock.release()
                    return

                self.player.play()
                self.player.audio_set_volume(int(self.volume))
                self.nowPlaying = audio.title
                self.totalTimeLabel.setText(audio.duration)
                h, m, s = audio.duration.split(":")
                duration = int(h) * 3600 + int(m) * 60 + int(s)
                # print(duration)
                ticker = 1 / duration
                try:
                    self.nowPlayingLabel.setText(
                        f"Now Playing: {self.nowPlaying}")
                    self.logBrowser.append(f"Now playing: {self.nowPlaying}")
                    with open("nowPlaying.txt", "w", encoding="utf-8") as f:
                        f.write(self.nowPlaying + '   ')
                except:
                    self.nowPlaying = self.nowPlayingLabel.encode(
                        "unicode_escape")
                    self.nowPlayingLabel.setText(
                        f"Now Playing: {self.nowPlaying}")
                    self.logBrowser.append(f"Now playing: {self.nowPlaying}")
                    with open("nowPlaying.txt", "w", encoding="utf-8") as f:
                        f.write(str(self.nowPlaying) + '   ')
                self.playButton.setEnabled(False)
                self.threadLock.release()
                self.deleteButton.setEnabled(False)
                self.skipButton.setEnabled(False)
                try:
                    ticker2 = int(link[1]) / duration
                    self.songPosition = ticker2
                    self.player.set_position(ticker2)
                    self.timeSlider.setValue(self.songPosition)
                except IndexError:
                    pass
                # Redundant code, remove in future™
                for i in range(1):
                    self.songPosition += ticker
                    self.timeSlider.setValue(self.songPosition)
                    self.getTime()
                    time.sleep(1)
                if self.player.get_state() == State.Ended:
                    self.nowPlayingLabel.setText("RETRYING CONNECTION")
                    self.play()
                else:
                    self.update()
                self.skipButton.setEnabled(True)
                self.deleteButton.setEnabled(True)
                try:
                    self.songPosition = ticker2 + (1 * ticker)
                    self.timeSlider.setValue(ticker2 + (1 * ticker))
                except UnboundLocalError:
                    self.songPosition = ticker * 1
                    self.timeSlider.setValue(ticker * 1)
                timeout = time.time() + TIMEOUT
                while self.player.get_state(
                ) == State.Playing or self.player.get_state() == State.Paused:
                    if not self.paused:
                        self.songPosition += ticker
                        self.timeSlider.setValue(self.songPosition)
                        # print(self.songPosition)
                        # print(self.timeSlider.value())
                        self.getTime()
                        time.sleep(1)
                    if time.time() > timeout:
                        global TIME_LIMIT
                        if TIME_LIMIT:
                            break
                    if not self.run:
                        self.player.stop()
                        sys.exit()
                self.songPosition = 0
                self.timeSlider.setValue(0)
                self.player.stop()
                self.play()
            except Exception as e:
                self.threadLock.release()
                self.errorDialog.setWindowTitle("Warning")
                self.errorDialog.showMessage(str(e))
                self.update()
                self.play()
        else:
            self.playButton.setEnabled(True)
            self.nowPlayingLabel.setText("Now Playing:")
            self.currentTimeLabel.setText("00:00:00")
            self.totalTimeLabel.setText("00:00:00")
            with open("nowPlaying.txt", "w", encoding="utf-8") as f:
                f.write("No songs playing currently.   ")
Exemple #24
0
class Music_Player():
    def __init__(self):
        self.player = None
        self.playing = False
        self.song_dictionary = {}
        self.current_playlist = []
        self.music_dirs = []
        self.current_song_index = 0
        self.is_online = False
        self.muted = False
        self.current_volume = 100

    def start(self, music_dirs):
        self.music_dirs = music_dirs
        self.create_playlist()
        self.vlcInstance = Instance('--novideo')
        self.player = self.vlcInstance.media_player_new()

    def create_playlist(self):
        self.current_playlist = []
        path_list = []

        for music_dir in self.music_dirs:
            path_list = self.get_songs_in_folder(music_dir, path_list)

        for song_path in path_list:
            song_name = self.get_song_name(song_path)
            self.song_dictionary[song_name] = song_path
            self.current_playlist.append(song_name)

        self.current_song_index = 0
        self.is_online = False

    def set_custom_playlist(self, list):
        self.current_playlist = list
        self.current_song_index = 0

    def create_online_dictionary(self, song_name):
        self.song_dictionary = yt_search(song_name)
        self.current_playlist = []

        for song in self.song_dictionary.keys():
            self.current_playlist.append(song)

        self.current_song_index = 0
        self.is_online = True

    def shuffle_playlist(self):
        random.shuffle(self.current_playlist)
        self.current_song_index = 0

    def next(self):
        if len(self.current_playlist) > 0:
            self.current_song_index = (self.current_song_index + 1) % len(
                self.current_playlist)

            if self.playing:
                self.stop()
                self.play()

    def skip_to_song(self, index):
        self.current_song_index = index % len(self.current_playlist)

    def previous(self):
        if len(self.current_playlist) > 0:
            self.current_song_index = (self.current_song_index - 1) % len(
                self.current_playlist)

            if self.playing:
                self.stop()
                self.play()

    def stop(self):
        self.player.stop()
        self.playing = False

    def play(self):

        if self.current_playlist:
            if self.playing == False:
                song_name = self.current_playlist[self.current_song_index]
                song = self.song_dictionary[song_name]

                if self.is_online == True:
                    song = yt_stream(song)

                media = self.vlcInstance.media_new(song)
                media.get_mrl()
                self.player.set_media(media)
                self.player.play()
                self.playing = True
                time.sleep(1)

            else:
                self.player.pause()

    def get_duration(self):
        song_duration = self.player.get_length() / 1000
        return time.strftime('%H:%M:%S', time.gmtime(song_duration))

    def get_time(self):
        song_time = self.player.get_time() / 1000
        return time.strftime('%H:%M:%S', time.gmtime(song_time))

    def pause(self):
        self.player.pause()

    def get_state(self):
        return self.player.get_state()

    def get_songs_in_folder(self, path, song_list):

        for file in os.listdir(path):
            file_path = os.path.join(path, file)

            if (os.path.isdir(file_path)):
                self.get_songs_in_folder(file_path, song_list)
            elif (file_path.endswith('.mp3')):
                song_list.append(file_path)

        song_list = list(dict.fromkeys(song_list))

        return song_list

    def get_current_playlist(self):
        return self.current_playlist

    def get_song_name(self, song):
        # if (song.startswith('https://www.youtube.com/watch')):
        #     return yt_get_title(song)
        if platform.system() == 'Windows':
            return song.split('\\')[-1][:-4]
        else:
            return song.split('/')[-1][:-4]

    def get_current_song_name(self):
        if not self.current_playlist:
            return ""
        return self.current_playlist[self.current_song_index]

    def get_current_song_path(self):
        if not self.current_playlist:
            return ""

        song_name = self.current_playlist[self.current_song_index]
        song = self.song_dictionary[song_name]
        return song

    def get_elapsed_percentage(self):
        percentage = self.player.get_position() * 100
        return percentage

    def get_volume(self):
        return self.player.audio_get_volume()

    def set_volume(self, volume):
        self.current_volume = volume
        if self.muted == False:
            self.player.audio_set_volume(self.current_volume)

    def mute(self):

        if self.muted == True:
            self.player.audio_set_volume(self.current_volume)
            self.muted = False
        else:
            self.player.audio_set_volume(0)
            self.muted = True

    def seek(self, position):
        self.player.set_position(position)
class piTunesController:


	def __init__(self):
		pyspeaker.initSay()
		print "Init piTunes controller"
		self.client = soundcloud.Client(client_id='8da91e376c359e86e2ef2ea5f3008514')


		self.client = soundcloud.Client(client_id='8da91e376c359e86e2ef2ea5f3008514',
                           client_secret='7b38fab0df5b9d131d388d7118c43467',
                           username='******',
                           password='******')
		self.still_running = True

		self.instance = Instance("")
		self.player = self.instance.media_player_new()

	def announce_track(self,track_request,suggested_track):

		username = 	track_request['username']
		message = track_request['message']	
		title = suggested_track['track_details'].title
		description = suggested_track['track_details'].description	
		
		if username:
			self.say("This ones going out for  %s" % username)
			time.sleep(2)

		if (message and username):
			self.say("%s has asked me to say %s" % (username, message))
			time.sleep(2)

		if title:
			self.say("Its a cheeky little number called  %s" % title)
			time.sleep(2)
		self.say("Let me hear you say yo")
		time.sleep(2)

	def call_request_api(self):
		# return dummy request for now

		#request = {}
		#request['username'] = '******'
		#request['search'] = self.default_search
		#request['message'] = 'this one is for my mum'

		#print request
		url = "http://pitunes.herokuapp.com/api/next"
		resp = urllib2.urlopen(url)
		response_string = resp.read()
		print response_string
		request = json.loads(response_string)

		return request
		



	def filler_speech(self):
		self.say("Filler time")

	def play_track(self,track):
		try:
			url = track['stream_url']
			
			print "Playing:" + url 

			media = self.instance.media_new(url)

			self.player.set_media(media)
			self.player.play()
			time.sleep(5)
			
			# wait until track completes
			while(self.player.is_playing()):
				# sleep for a bit
				time.sleep(2)

			self.player.stop()

		except NameError:
			print('NameError: %s (%s vs LibVLC %s)' % (sys.exc_info()[1],
					__version__,
					libvlc_get_version()))
			sys.exit(1)

	def say(self, text):
		pyspeaker.say(text, "-ven+m8 -k5 -s150")
		time.sleep(2)

	def run(self):
		print "Starting piTunes controller"
		self.say("Starting piTunes controller")

		while(self.still_running):

			# get next track
			next_track_req = self.call_request_api()

			# if no track suggested
			if(next_track_req==None):
				self.filler_speech()
			else:
				# search soundcloud
				track=self.search_soundcloud(next_track_req['search'])

				if(track==None):
					self.filler_speech()

				# announce track
				self.announce_track(next_track_req, track)
				
				# play track
				self.play_track(track)

				# filler speak
				self.filler_speech()

			# repeat forever?

	def search_soundcloud(self,search):
		# fetch track to stream

		print "Searching for %s" % search
		self.say("Searching for %s" % search)

		#tracks = self.client.get('/tracks', q=search,duration={0:60000})
		tracks = self.client.get('/tracks', q=search,duration={'from':0, 'to':60000})
		if(tracks==None):
			return None

		total_tracks = len(tracks)

		print "Found %d" % total_tracks

		random_id = int(random.random()*total_tracks)
		print "Random_id:" + str(random_id)
		# get the tracks streaming URL
		track = tracks[random_id]

		stream_url = self.client.get(track.stream_url, allow_redirects=False)

		suggested_track = {}
		suggested_track['stream_url']=stream_url.location
		suggested_track['track_details'] = track

		print "Suggested Track"		
		print "==============="		
		title = suggested_track['track_details'].title
		description = suggested_track['track_details'].description



		if title:
			print "Title:"+title

		if description:
			print "Description:"+description
	
		return suggested_track

	def set_default_search(self,search):
		# fetch track to stream
		self.default_search = search
class GooglePlayMusicPlayer(object):
    def __init__(self,
                 account,
                 password,
                 shuffle=False,
                 loop=0,
                 volume=50,
                 muted=False,
                 library_update=False,
                 debug=False):
        self._api = Mobileclient(debug_logging=False)
        self._vlc = Instance()

        self._library_songs = None
        self._library_playlists = None

        self._queue_trackDict = []
        self._queue_index = -99  # -1 = finished playing queue, -99 = empty queue, -2 = fresh start
        self._queue_history_backward = []
        self._queue_history_forward = []
        self._queue_shuffle_on = shuffle
        self._queue_loop_mode = loop  # 0 = loop off, 1 = loop all, 2 = repeat one

        self._player = None
        self._player_state = 'stopped'  # stopped, playing, or paused
        self._player_volume = volume
        self._player_volume_muted = muted

        self._command_dict = available_commands
        self._id_text = '[GooglePlayMusicPlayer] '
        self._is_playing_before_pausing_for_command = False
        self._last_executed_command = 'stop'
        self._debug = debug

        self._api.login(account, password, Mobileclient.FROM_MAC_ADDRESS)
        self._library_load_data(library_update)

    ### LIBRARY Functions ###
    def _library_load_data(self, force_online=False):
        if (not force_online) and os.path.isfile('songs.json'):
            # Load from file
            if self._debug is True:
                print(self._id_text + 'Found local song data.')
            with open('songs.json') as input_file:
                self._library_songs = json.load(input_file)
        else:
            self._library_songs = self._api.get_all_songs()
            # Save to file
            with open('songs.json', 'w') as output_file:
                json.dump(self._library_songs, output_file)

        if (not force_online) and os.path.isfile('playlists.json'):
            # Load from file
            if self._debug is True:
                print(self._id_text + 'Found local playlist data.')
            with open('playlists.json') as input_file:
                self._library_playlists = json.load(input_file)
        else:
            self._library_playlists = self._api.get_all_user_playlist_contents(
            )
            # Save to file
            with open('playlists.json', 'w') as output_file:
                json.dump(self._library_playlists, output_file)

    def _library_get_song_details(self, track_id):
        for song_dict in self._library_songs:
            if track_id == song_dict['id']:
                return song_dict['artist'] + " - " + song_dict['title']
        return "Unknown Artist - Unknown Title"

    ### End LIBRARY Functions ###

    ### QUEUE Functions ###
    def _queue_load_playlist(self, playlist):
        playlist_name = playlist.strip().lower()
        self._queue_reset()

        for playlist_dict in self._library_playlists:
            actual_playlist_name = playlist_dict['name'].strip().lower()
            if playlist_name in actual_playlist_name:
                if self._debug is True:
                    print(self._id_text + "Found match...",
                          playlist_dict['name'])
                for track_dict in playlist_dict['tracks']:
                    self._queue_trackDict.append(track_dict)
                if len(self._queue_trackDict) != 0:
                    self._queue_index = -2
                return playlist_dict['name']
            else:
                if self._debug is True:
                    print(self._id_text + "Found...", playlist_dict['name'])
        if self._debug is True:
            print(self._id_text +
                  "Nothing matches... Playlist was not loaded...")
        return None

    def _queue_reset(self):
        self._controller_stop()
        self._queue_trackDict = []
        self._queue_index = -99
        self._queue_history_backward = []
        self._queue_history_forward = []

    def _queue_reset_index(self):
        if self._queue_shuffle_on is True:
            self._queue_index = self._queue_random_index()
        else:
            self._queue_index = 0

    def _queue_reset_history(self):
        self._queue_history_backward = []
        self._queue_history_forward = []

    def _queue_random_index(self):
        while True:
            random_number = random.randrange(0, len(self._queue_trackDict))
            if (self._queue_index != random_number) or (len(
                    self._queue_trackDict) == 1):
                break
        return random_number

    def _queue_next(self):
        if len(self._queue_trackDict) == 0:
            self._queue_index = -99
            return

        if self._queue_loop_mode == 2:  # repeat one
            return

        if self._queue_shuffle_on is True:
            self._queue_history_backward.append(self._queue_index)
            if len(self._queue_history_forward) > 0:
                self._queue_index = self._queue_history_forward.pop()
            else:
                self._queue_index = self._queue_random_index()
        else:
            self._queue_index += 1
            if (self._queue_index >= len(
                    self._queue_trackDict)) and (self._queue_loop_mode == 0):
                self._queue_index = -1
            else:
                self._queue_index %= len(self._queue_trackDict)

    def _queue_previous(self):
        if len(self._queue_trackDict) == 0:
            self._queue_index = -99
            return

        if self._queue_shuffle_on is True:
            if len(self._queue_history_backward) > 0:
                self._queue_history_forward.append(self._queue_index)
                self._queue_index = self._queue_history_backward.pop()
        else:
            self._queue_index = max(0, self._queue_index - 1)

    def _queue_get(self):
        if self._queue_index == -2:
            self._queue_reset_index()
            return self._queue_get()
        if self._queue_index == -1:
            self._queue_reset_index()
            return None
        if (self._queue_index < 0) or (self._queue_index >= len(
                self._queue_trackDict)):
            return None
        return self._queue_trackDict[self._queue_index]

    ### End QUEUE Functions ###

    ### PLAYER & CONTROLLER Functions ###
    def _controller_play_song(self, song_dict):
        stream_url = self._api.get_stream_url(song_dict['trackId'])
        self._player = self._vlc.media_player_new()
        media = self._vlc.media_new(stream_url)
        self._player.set_media(media)
        if self._player_volume_muted is True:
            self._player.audio_set_volume(0)
        else:
            self._player.audio_set_volume(self._player_volume)
        self._player.play()
        self._player_state = 'playing'

        self._player.event_manager().event_attach(
            EventType.MediaPlayerEndReached,
            self._controller_finish_and_play_next)

        song_info_string = self._library_get_song_details(song_dict['trackId'])
        print(self._id_text + "Playing... " + song_info_string + " (" +
              song_dict['id'] + ")")

    def _controller_play(self):
        if self._player_state == 'stopped':
            song_dict = self._queue_get()
            if song_dict == None:
                return
            self._controller_play_song(song_dict)
        elif self._player_state == 'playing':
            return
        elif self._player_state == 'paused':
            self._player.set_pause(0)
            self._player_state = 'playing'

    def _controller_pause(self):
        if self._player_state == 'playing':
            self._player.set_pause(1)
            self._player_state = 'paused'

    def _controller_stop(self):
        if self._player_state in ['playing', 'paused']:
            self._player.stop()
            self._player_state = 'stopped'

    def _controller_finish_and_play_next(self, event):
        self._player_state = 'stopped'
        self._api.increment_song_playcount(
            self._queue_trackDict[self._queue_index]['id'])
        self._controller_next()
        self._controller_play()

    def _controller_next(self):
        saved_player_state = self._player_state
        self._controller_stop()
        self._queue_next()
        if saved_player_state != 'stopped':
            self._controller_play()

    def _controller_previous(self):
        saved_player_state = self._player_state
        self._controller_stop()
        self._queue_previous()
        if saved_player_state != 'stopped':
            self._controller_play()

    def _controller_shuffle(self, mode):  # mode False = off, mode True = on
        self._queue_shuffle_on = mode
        self._queue_reset_history()

    def _controller_loop(
            self,
            mode):  # mode 0 = loop off, mode 1 = loop all, mode 2 = repeat one
        self._queue_loop_mode = mode

    def _controller_volume_adjust(self, direction, amount):
        if direction is 'up':
            self._player_volume = min(self._player_volume + amount, 100)
        else:
            self._player_volume = max(0, self._player_volume - amount)

        if self._player is not None:
            self._player.audio_set_volume(self._player_volume)
        self._player_volume_muted = False

    def _controller_volume_mute(self):
        if self._player_volume_muted is False:
            if self._player is not None:
                self._player.audio_set_volume(0)
            self._player_volume_muted = True

    def _controller_volume_unmute(self):
        if self._player_volume_muted is True:
            if self._player is not None:
                self._player.audio_set_volume(self._player_volume)
            self._player_volume_muted = False

    ### End PLAYER & CONTROL Functions ###

    def load_playlist(self, playlist_name):
        self._last_executed_command = 'load'
        return self._queue_load_playlist(playlist_name)

    def play(self):
        self._last_executed_command = 'play'
        self._controller_play()

    def pause(self):
        self._last_executed_command = 'pause'
        self._controller_pause()

    def stop(self):
        self._last_executed_command = 'stop'
        self._controller_stop()

    def next(self):
        self._last_executed_command = 'next'
        self._controller_next()

    def previous(self):
        self._last_executed_command = 'previous'
        self._controller_previous()

    def shuffle(self, command):
        self._last_executed_command = 'shuffle'
        if command in [0, 1]:
            self._controller_shuffle(True if command is 1 else False)
        elif command is 2:
            return self._queue_shuffle_on

    def loop(self, command):
        self._last_executed_command = 'loop'
        if command in [0, 1, 2]:
            self._controller_loop(command)
        elif command is 3:
            return self._queue_loop_mode

    def volume_adjust(self, direction, amount):
        self._last_executed_command = 'volume'
        if direction in ['up', 'down']:
            self._controller_volume_adjust(direction, amount)

    def mute(self):
        self._last_executed_command = 'mute'
        self._controller_volume_mute()

    def unmute(self):
        self._last_executed_command = 'unmute'
        self._controller_volume_unmute()

    def get_command_list(self):
        return self._command_dict.keys()

    def pause_for_command(self):
        if self._player_state is 'playing':
            self._is_playing_before_pausing_for_command = True
            self._controller_pause()
        else:
            self._is_playing_before_pausing_for_command = False

    def resume_after_command(self, force):
        if self._is_playing_before_pausing_for_command is True:
            if (force is True) or (self._last_executed_command
                                   not in ['play', 'pause', 'stop']):
                self._controller_play()

    # from google assistant voice command control (import this file from google AIY)
    def run_command(self, action):
        if 'play' in action:
            playlist = action.replace("play", "").strip()
            if self.load_playlist(playlist) is None:
                return ('I am not able to find ' + playlist)
            self.play()
        elif self._command_dict[action] == 'play':
            self.play()
        elif self._command_dict[action] == 'pause':
            self.pause()
        elif self._command_dict[action] == 'stop':
            self.stop()
        elif self._command_dict[action] == 'next':
            self.next()
        elif self._command_dict[action] == 'previous':
            self.previous()
        elif self._command_dict[action] == 'shuffle off':
            self.shuffle(0)
        elif self._command_dict[action] == 'shuffle on':
            self.shuffle(1)
        elif self._command_dict[action] == 'shuffle status':
            s = 'on' if self.shuffle(2) is True else 'off'
            return ('Shuffle is ' + s)
        elif self._command_dict[action] == 'looping off':
            self.loop(0)
        elif self._command_dict[action] == 'looping all':
            self.loop(1)
        elif self._command_dict[action] == 'looping one':
            self.loop(2)
        elif self._command_dict[action] == 'looping status':
            s = self.loop(3)
            msg = 'is off' if s is 0 else (
                'all songs' if s is 1 else 'this song')
            return ('looping ' + msg)
        elif self._command_dict[action] == 'volume up':
            self.volume_adjust('up', 10)
        elif self._command_dict[action] == 'volume down':
            self.volume_adjust('down', 10)
        elif self._command_dict[action] == 'mute':
            self.mute()
        elif self._command_dict[action] == 'unmute':
            self.unmute()
        else:  # probably won't get here
            print(self._id_text + 'Not a valid action...')
            return ('I don\'t know what to do.')
from vlc import Instance as VLC
from pathlib import Path
from sys import argv

if len(argv) > 1:
    file = Path(argv[1])
    if file.is_file():
        cmd = [
            "file://{}".format(file.absolute()),
            "sout=#duplicate{dst=rtp{dst=127.0.0.1,port=1234}}",
            "no-sout-rtp-sap", "no-sout-standard-sap", "sout-keep"
        ]
        print("start streaming with arguments: {}".format(cmd))
        vlc = VLC()
        media = vlc.media_new(*cmd)
        print(media.get_mrl())

        player = vlc.media_player_new()
        player.set_media(media)
        player.play()
 def play(self):
     with open('urllist.txt', 'r') as f:
         url = f.readline().strip()
     if url:
         try:
             self.threadLock.acquire()
             video = pafy.new(url)
             best = video.getbest()
             playurl = best.url
             vInstance = Instance('--novideo')
             self.player = vInstance.media_player_new()
             media = vInstance.media_new(playurl)
             self.player.set_media(media)
             self.player.play()
             self.player.audio_set_volume(int(self.volume))
             self.nowPlaying = video.title
             self.durationLabel.config(text=video.duration)
             h, m, s = video.duration.split(':')
             duration = int(h) * 3600 + int(m) * 60 + int(s)
             ticker = 1 / duration
             try:
                 self.nowPlayingLabel.config(
                     text=f'Now Playing: {self.nowPlaying}')
                 with open('nowPlaying.txt', 'w', encoding='utf-8') as f:
                     f.write(self.nowPlaying + '   ')
             except:
                 self.nowPlaying = self.nowPlaying.encode('unicode_escape')
                 self.nowPlayingLabel.config(
                     text=f'Now Playing: {self.nowPlaying}')
                 with open('nowPlaying.txt', 'w', encoding='utf-8') as f:
                     f.write(str(self.nowPlaying) + '   ')
             self.playButton.config(state='disabled')
             self.threadLock.release()
             self.shuffleButton.config(state='disabled')
             self.deleteButton.config(state='disabled')
             self.nextButton.config(state='disabled')
             for i in range(3):
                 self.songPosition += ticker
                 self.musicScrubber.set(self.songPosition)
                 self.get_time()
                 time.sleep(1)
             if self.player.get_state() == State.Ended:
                 self.nowPlayingLabel.config(text='RETRYING CONNECTION')
                 self.play()
             else:
                 self.update()
             self.shuffleButton.config(state='normal')
             self.deleteButton.config(state='normal')
             self.nextButton.config(state='normal')
             self.songPosition = ticker * 3
             self.musicScrubber.set(ticker * 3)
             while self.player.get_state(
             ) == State.Playing or self.player.get_state() == State.Paused:
                 if self.paused == False:
                     self.songPosition += ticker
                     self.musicScrubber.set(self.songPosition)
                     self.get_time()
                     time.sleep(1)
                 if self.run == False:
                     self.player.stop()
                     sys.exit()
             self.songPosition = 0
             self.musicScrubber.set(0)
             self.player.stop()
             self.play()
         except Exception as error:
             self.threadLock.release()
             tkinter.messagebox.showwarning(title='Warning', message=error)
             self.update()
             self.play()
     else:
         self.playButton.config(state='normal')
         self.nowPlayingLabel.config(text='Now Playing:')
         self.durationLabel.config(text='00:00:00')
         self.timeLabel.config(text='00:00:00 /')
         with open('nowPlaying.txt', 'w', encoding='utf-8') as f:
             f.write(
                 'No songs playing. Donate to have your song played on stream.   '
             )