示例#1
0
def main():
    # Spotify variables
    username = config.SPOTIFY_EMAIL
    spotify_id = config.SPOTIFY_ID
    spotify_secret = config.SPOTIFY_SECRET

    # Set API scope
    scope = "playlist-read-private, playlist-modify-private, playlist-modify-public"

    # Get auth token
    token = util.prompt_for_user_token(username,
                                       scope,
                                       client_id=spotify_id,
                                       client_secret=spotify_secret,
                                       redirect_uri='http://localhost/')

    # Authenticate
    sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials(
        client_id=spotify_id, client_secret=spotify_secret))
    data_dir = 'data'

    track_data = pd.read_csv(os.path.join(data_dir, "wmw_tracks.csv"))

    playlist = Playlist(track_data, sp, token, model_type="LSTM")

    playlist.post_playlist()
示例#2
0
    def create_playlist():  # pylint: disable=unused-variable
        """
            Handles button press from top tracks visualization and 
            creates Spotify playlist with top tracks
        """
        # Create playlist from top tracks data using Playlist class
        spotitude_playlist = Playlist(spotify)
        spotitude_playlist.create_spotitude_playlist(time_range, data["id"].tolist())
        print(
            f"Playlist '{spotitude_playlist.name}' created.\n{spotitude_playlist.url}"
        )

        # Change 'Create Playlist' to 'Open Playlist' and write hidden URL to html file
        with open("index.html", "r") as spot_html:
            filedata = spot_html.read()
            filedata = filedata.replace("Create Playlist", "Open Playlist")
            # Change onclick action to open playlist url, also possible independent from python script
            filedata = filedata.replace(
                "onclick='create_playlist()'",
                f"onclick=\"window.open('{spotitude_playlist.url}','_blank','resizable=yes')",
            )

        with open("index.html", "w") as spot_html:
            spot_html.write(filedata)

        # pylint: disable=no-member
        eel.open_url(spotitude_playlist.url)  # open playlist in new window
示例#3
0
    def test_if_packing_songs_works(self):
        code_songs = Playlist(name="Code Imam")
        s = Song(title="Odin",
                 artist="Manowar",
                 album="The Sons of Odin",
                 length="3:44")
        c = Song('Snow', 'RHCP', 'Stadium Arcadium', '5:50')
        m = Song('Under the Bridge', 'RHCP', 'Blood Sugar Sex Magik', '4:25')
        ls = [s, c, m]
        code_songs.add_songs(ls)
        data = [{
            "title": "Odin",
            "artist": "Manowar",
            "album": "The Sons of Odin",
            "length": "3:44"
        }, {
            "title": "Snow",
            "artist": "RHCP",
            "album": "Stadium Arcadium",
            "length": "5:50"
        }, {
            "title": "Under the Bridge",
            "artist": "RHCP",
            "album": "Blood Sugar Sex Magik",
            "length": "4:25"
        }]

        res = code_songs.pack_songs(data)

        exp = code_songs.song_list

        self.assertEqual(res, exp)
 def setUp(self):
     self.playlist = Playlist('my_playlist')
     self.untitled = Playlist()
     self.song_1 = Song('Hells Bells', 'AC/DC', 'rough and though', 4, 400,
                        256)
     self.song_2 = Song('For Whom the Bell Tolls', 'Metallica',
                        'For Whom the Bell Tolls', 5, 500, 320)
示例#5
0
    def test_as_json_dict(self):
        playlist = Playlist(name='Code', repeat=True)
        playlist._songs = [self.song, self.new_song1]

        expected = {
            'name':
            'Code',
            'repeat':
            True,
            'shuffle':
            False,
            'songs': [{
                'title': 'Odin',
                'artist': 'Manowar',
                'album': 'The Sons of Odin',
                'length': '03:44'
            }, {
                'title': 'Him & I',
                'artist': 'G-eazy',
                'album': '',
                'length': '04:28'
            }]
        }

        self.assertEqual(playlist.as_json_dict(), expected)
示例#6
0
    def test_if_next_song_gives_error_if_song_list_ends_with_repeat_and_shuffle_off(
            self):

        code_songs = Playlist(name="Code")
        s = Song(title="Odin",
                 artist="Manowar",
                 album="The Sons of Odin",
                 length="3:44")
        c = Song('Snow', 'RHCP', 'Stadium Arcadium', '5:50')
        m = Song('Under the Bridge', 'RHCP', 'Blood Sugar Sex Magik', '4:25')
        err = None
        ls = [s, c, m]

        code_songs.add_songs(ls)

        code_songs.next_song()
        code_songs.next_song()
        code_songs.next_song()

        try:
            code_songs.next_song()
        except Exception as exc:
            err = exc

        self.assertIsNotNone(err)
        self.assertEqual(str(err), 'No more songs in playlist')
示例#7
0
def makePlaylist(token, username):
    "Function returns list containing song library"

    sp = spotipy.Spotify(auth=token)  #create Spotify object
    songs = []
    offset = 0  #this variable determines index in song library at which to begin song fetch
    playlist = Playlist(username, [])
    #begin fetching songs from library
    results = sp.current_user_saved_tracks(20, offset)
    while (not (results['items']
                == [])):  #while there are still songs left in library
        for item in results['items']:
            track = item['track']
            songs.append(track)

        #increase offset to fetch next batch of songs, then fetch
        offset += 20
        results = sp.current_user_saved_tracks(20, offset)
    #create playlist object from json string of songs
    for song in songs:
        artists = []
        for artist in song['artists']:
            artists.append(artist['name'])
        track = Song(song['name'], artists)
        playlist.add(track)
    return playlist
示例#8
0
def playlist_download(dir, krc, lrc, onlylyric):
    playlist = Playlist("default")
    songs = playlist.get_songs()

    for song in songs:
        if not onlylyric:
            link = playlist.get_download_link(song, api.query_download_link)
            _, ext = os.path.splitext(link)
            file_name = api.music.song_file_name_noext(song) + ext
            path = os.path.join(dir, file_name)

            # 以后判存的方式需要改进
            if os.path.exists(path):
                print("%s已经存在,无需下载。" % path)
            else:
                print("开始下载%s" % path)
                try:
                    download.download(link, path)
                except download.CommandNotFoundError as e:
                    print("错误: %s" % str(e))

        lyric_types = list()
        if lrc: lyric_types.append("lrc")
        if krc: lyric_types.append("krc")
        for type_ in lyric_types:
            file_name = api.music.song_file_name_noext(song) + "." + type_
            path = os.path.join(dir, file_name)
            print("开始保存歌词:%s" % file_name)
            text = api.query_lyric(song, type_)
            with open(path, "wb") as f:
                f.write(text)
示例#9
0
def global_config():
    logging.basicConfig(level=logging.ERROR)
    api.cache.set_cache_file(
        os.path.join(_DIR_, "data", "tmp", "api-cache.json"))
    api.cache.set_cache_duration(24 * 60 * 60)
    Playlist.set_default_store_dir("data/playlist")
    command.CommandBuffer.set_default_store_dir("data/tmp")
示例#10
0
 def test_total_length(self):
     new_playlist = Playlist("my_playlist")
     harvester_song = Song("Harvester of sorrow", "Metallica", "...And justice for all", 3, 300, 192)
     enter_song = Song("Enter sandman", "Metallica", "Balck album", 2, 300, 192)
     new_playlist.songs.append(harvester_song)
     new_playlist.songs.append(enter_song)
     self.assertEqual(new_playlist.total_length(), 600)
 def setUp(self):
     self.code_songs = Playlist(name="Code", repeat=True, shuffle=True)
     self.song = Song(title="Odin",
                      artist="Manowar",
                      album="The Sons of Odin",
                      length="3:44")
     self.code_songs.add_song(self.song)
示例#12
0
	def test_when_no_songs_then_return_empty_histogram(self):
		playlist = Playlist('my playlist')
		expected_result = {}

		result = playlist.artists()

		self.assertEqual(result, expected_result)			
 def test_remove_song(self):
      song = Song(title="Odin", artist="Manowar", album="The Sons of Odin", length="1:30:44")
      code_songs = Playlist(name="Code", repeat=False, shuffle=False)
      code_songs.add_song(song)
      self.assertTrue(song in code_songs.song_list)
      code_songs.remove_song(song)
      self.assertTrue(song not in code_songs.song_list)
 def API_renamePlaylist(self, playlist_id, name, request):
     try:
         Playlist.rename(playlist_id, name)
     except ValueError as e:
         raise
     self.needs_push_update = True
     request.finish()
示例#15
0
    def test_if_unpack_songs_is_working(self):
        code_songs = Playlist(name="Code", shuffle=True)
        s = Song(title="Odin",
                 artist="Manowar",
                 album="The Sons of Odin",
                 length="3:44")
        c = Song('Snow', 'RHCP', 'Stadium Arcadium', '5:50')
        m = Song('Under the Bridge', 'RHCP', 'Blood Sugar Sex Magik', '4:25')
        ls = [s, c, m]

        code_songs.add_songs(ls)

        res = code_songs.unpack_songs()

        exc = [{
            'title': 'Odin',
            'artist': 'Manowar',
            'album': 'The Sons of Odin',
            'length': '3:44'
        }, {
            'title': 'Snow',
            'artist': 'RHCP',
            'album': 'Stadium Arcadium',
            'length': '5:50'
        }, {
            'title': 'Under the Bridge',
            'artist': 'RHCP',
            'album': 'Blood Sugar Sex Magik',
            'length': '4:25'
        }]

        self.assertEqual(res, exc)
示例#16
0
def playlist_add(song_no):
    song_no = int(song_no)
    song = g_song_buffer.get(song_no)
    playlist = Playlist()
    playlist.add_song(song)
    print("已添加歌曲:")
    print_nonl(dump_song(song, False, str(song_no) + "."))
 def start_saver (self):
     _debug_('start screensaver')
     self.screensaver_showing = TRUE
     if self.saver_type == 'xscreensaver':
         os.system('%s -no-splash &' % self.arg1)
         os.system('sleep 5 ; %s -activate' % self.arg2)
     elif self.saver_type == 'script':
         os.system('%s' % self.arg1)
     elif self.saver_type == 'ssr':
         self.pl = Playlist('ScreenSaver', playlist=self.arg1, display_type='image', repeat=True)
         self.pl.play(menuw=self.menuw)
     elif self.saver_type == 'fxd':
         mylist = fxditem.mimetype.parse(None, [self.arg1], display_type=self.arg2)
         if len(mylist) > 0:
             self.pl = mylist[0]
             arg = None
             if self.arg2 == 'image':
                 self.pl.repeat = 1
             elif self.arg2 == 'video':
                 arg = '-nosound -loop 0'
             self.pl.play(arg=arg, menuw=self.menuw)
         else:
             _debug_('saver thinks fxd blew up trying to parse?')
     else:
         _debug_('Unknown saver type to start.')
示例#18
0
def playlist_set_qualities_order():
    def dump_quality_order(order):
        s = ""
        for quality in order:
            s += quality + " "
        return s

    playlist = Playlist("default")
    print("当前优先级:%s" % dump_quality_order(playlist.quality_order))

    choise_list = [["128", "192", "320", "ape", "flac"],
                   ["128", "192", "320", "flac", "ape"],
                   ["ape", "flac", "320", "192", "128"],
                   ["flac", "ape", "320", "192", "128"],
                   ["320", "ape", "flac", "192", "128"],
                   ["320", "192", "flac", "ape", "128"],
                   ["320", "192", "ape", "flac", "128"],
                   ["320", "flac", "ape", "192", "128"]]
    print()
    print("选择序号来设置优先级")
    for i, order in enumerate(choise_list):
        print(str(i + 1) + "." + dump_quality_order(order))

    key = 0
    while (True):
        print("请选择序号:")
        key = int(input()) - 1
        if key < len(choise_list):
            break
        print("输入不在范围内")

    playlist.quality_order = choise_list[key]
示例#19
0
    def __init__(self, cover_dir, net_type='lan'):

        self.connected = False
        self.net_type = net_type
        self.proto = MpdProtocol()
        self.proto._event = self.dispatch_event
        self.status = {'state': 'stop'}
        self.playlist = Playlist(self)
        self.waiting = False
        self.calls = []
        self.cover_dir = cover_dir
        self._sources = [
            OrderedDict(
                sorted({
                    'Name': '_'.join((self.name, n)),
                    'Type': n,
                    'Visible': True
                }.items(),
                       key=lambda t: t[0])) for n in self.sources
        ]
        self.sourcexml = dict2xml(
            {'SourceList': [{
                'Source': n
            } for n in self._sources]})
        self.protocolinfo = self.mtlist = 'http-get:*:' + ''\
            .join([':*,http-get:*:'.join(self.mimetypes)]) + ':*'
 def load_playlist(self, playlist_config):
     """
     loading the playlist, allows us to override configuration playlist easily
     {
     "playlist": [],
     "shuffle": bool,
     "orderby": [ field, desc/_asc_ ]
     }
     """
     self.playlist_config = playlist_config
     self.playlist = Playlist([])
     if playlist_config:
         if not "tracks" in playlist_config:
             logging.error("no tracks key specified in playlist")
             logging.error(playlist_config)
             raise ValueError("no tracks key specified in playlist")
         self.playlist = Playlist(playlist_config["tracks"],
                                  self.settings().HOME_DIRECTORY,
                                  self.settings().get_config_path(),
                                  self.settings().SMARTBOT_HOME)
         for s in self.playlist.playlist:
             if "name" not in s:
                 s["name"] = self.voice().convert_filename_to_speech_text(s["url"])
         if "shuffle" in playlist_config:
             if playlist_config["shuffle"]:
                 self.playlist.shuffle()
         if "orderby" in playlist_config:
             self.playlist.sort(playlist_config["orderby"])
         if "start-track" in playlist_config:
             logging.debug("found start track, attempting to move position")
             if self.playlist.select_by_regex_only_if_earlier(playlist_config["start-track"]):
                 # poke these values in so we continue where we want to otherwise it will
                 # start at the NEXT track not this one.
                 self.json["user_state"] = { "track": self.playlist.get_current_track(), "seek": 0 }
                 logging.debug("setting user state to {}".format(self.json["user_state"]))
示例#21
0
    def __init__(self, options):

        self.player_cfg = ConfigParser.ConfigParser()
        self.player_cfg.read('config/player.cfg')

        print self.player_cfg

        # check for player settings in the configuration file
        if not self.player_cfg.has_section("player"):
            print("no player configuration found")
            sys.exit()

        # check for player settings in the configuration file
        if not self.player_cfg.has_section("screens"):
            print("no screen configuration found")
            sys.exit()

        self.screensaver_file = self.player_cfg.get("player", "screensaver")
        self.enable_screensaver = self.player_cfg.getboolean(
            "player", "enable_screensaver")

        # load play list
        self.playlist = Playlist()
        #        self.playlist.name(options["playlist"])
        #        self.playlist.load()

        # init variables
        self.basePath = os.path.dirname("..")

        self.api_name = options["api_name"]
        self.html_root = options["html_root"]
        self.current_dir = options["base_dir"]

        # create response object
        self.response = Response()
示例#22
0
    def __init__(self, dogvibes, id):
        self.dogvibes = dogvibes
        self.pipeline = gst.Pipeline("amppipeline" + id)

        # create the tee element
        self.tee = gst.element_factory_make("tee", "tee")
        self.pipeline.add(self.tee)

        # listen for EOS
        self.bus = self.pipeline.get_bus()
        self.bus.add_signal_watch()
        self.bus.connect('message', self.pipeline_message)

        # Create amps playqueue
        if Playlist.name_exists(dogvibes.ampdbname + id) == False:
            self.dogvibes.API_createPlaylist(dogvibes.ampdbname + id)
        tqplaylist = Playlist.get_by_name(dogvibes.ampdbname + id)
        self.tmpqueue_id = tqplaylist.id

        self.active_playlist_id = self.tmpqueue_id
        if (tqplaylist.length() > 0):
            self.active_playlists_track_id = tqplaylist.get_track_nbr(0).ptid
        else:
            self.active_playlists_track_id = -1
        self.fallback_playlist_id = -1
        self.fallback_playlists_track_id = -1

        # sources connected to the amp
        self.sources = []

        # the gstreamer source that is currently used for playback
        self.src = None

        self.needs_push_update = False
示例#23
0
 def __init__(self):
     super().__init__()
     self.__playlist = Playlist()
     self.__rds_updater = RdsUpdater()
     self.__resume_file = config.get_resume_file()
     self.__skip = threading.Event()
     self.output_stream = BytearrayIO()
示例#24
0
文件: signd.py 项目: rptr/libresign
 def __init__(self):
     self.running = True
     self.messages = queue.Queue()
     self.playlist = Playlist()
     self.locontrol = LibreOfficeController(self)
     # the interface we are using
     self.net_iiface = ""
示例#25
0
 def test_directory_not_recursive(self):
     trackList = [{
         "directory": "/home/pi/smartbot/media",
         "include-subdir": False
     }]
     p = Playlist(trackList)
     self.assertEqual(p.size(), 0)
示例#26
0
 def options(self, args):
     if (self.choice == 1):
         self.playlist = MusicCrawler(args[0]).generate_playlist()
     elif(self.choice == 2):
         self.playlist = Playlist(args[0])
     elif(self.choice == 3):
         self.playlist = Playlist.load(args[0])
     elif(self.choice == 4):
         self.playlist.save(args[0])
     elif(self.choice == 5):
         song = Song(args[0], args[1], args[2], int(
             args[3]), int(args[4]), int(args[5]))
         self.playlist.add_song(song)
     elif(self.choice == 6):
         song = Song(args[0], args[1], args[2], int(
             args[3]), int(args[4]), int(args[5]))
         self.playlist.remove_song(song)
     elif(self.choice == 7):
         self.playlist.remove_disrated(int(args[0]))
     elif(self.choice == 8):
         self.playlist.remove_bad_quality()
     elif(self.choice == 9):
         print(self.playlist.show_artist())
     elif(self.choice == 10):
         print(self.playlist)
     elif(self.choice == 11):
         self.list_options()
     else:
         print("Enter a valid command")
示例#27
0
    def __init__(self, parent=None):
        super(Player, self).__init__(parent)

        self.duration = 0
        self.volume = 50

        self.player = QMediaPlayer()
        self.playlist = Playlist(self)
        self.videoWidget = VideoWidget()
        self.next_url = QUrl()
        self.context_menu = QMenu(self)
        self.display_splitter = QSplitter(Qt.Horizontal)
        self.repeat_control = RepeatControl(parent=self)
        self.repeat_control.get_player_position = self.player.position
        self.repeat_control.set_position_to_player = self.player.setPosition
        self.player.positionChanged.connect(self.repeat_control.set_pos)

        self.setAcceptDrops(True)

        std_icon = self.style().standardIcon
        self.play_button = create_flat_button(std_icon(QStyle.SP_MediaPlay))
        self.stopButton = create_flat_button(std_icon(QStyle.SP_MediaStop), '')
        self.backwardButton = create_flat_button(
            std_icon(QStyle.SP_MediaSkipBackward), '')
        self.forwardButton = create_flat_button(
            std_icon(QStyle.SP_MediaSkipForward), '')

        self.order_list = self.repeat_control.menu()
        self.order_list.setFixedWidth(115)

        self.playback_rate_menu = QComboBox()
        self.playback_rate_menu.addItems(
            ('0.5x', '0.75x', '0.9x', '1.0x', '1.1x', '1.25x', '1.5x'))
        self.playback_rate_menu.setCurrentText('1.0x')

        self.muteButton = create_flat_button(
            std_icon(QStyle.SP_MediaVolume if not self.player.isMuted() else
                     QStyle.SP_MediaVolumeMuted))

        self.volumeBar = QSlider(Qt.Horizontal)
        self.volumeBar.setRange(0, 100)
        self.volumeBar.setValue(self.volume)

        self.labelVolume = QLabel(str(self.volume))
        self.labelVolume.setMinimumWidth(24)

        self.statusInfoLabel = QLabel()

        self.seekBar = QSlider(Qt.Horizontal)
        self.seekBar.setRange(0, self.player.duration() / 1000)

        self.labelTotalTime = QLabel('00:00')
        self.labelCurrentTime = QLabel('00:00')

        self.create_layout()
        self.create_connections()

        self.player.setVideoOutput(self.videoWidget)
        self.videoWidget.show()
 def setUp(self):
     self.playlist = Playlist("TestPlaylist")
     self.song = Song("Thunderstruck", "ACDC", "The Razors Edge", 5, 271.8,
                      320)
     self.song2 = Song("Nothing else matters", "Metallica", "IDK", 0, 271.8,
                       320)
     self.playlist.add_song(self.song)
     self.playlist.add_song(self.song2)
    def test_total_length(self):
        playlist = Playlist("TestPlaylist")
        song1 = Song("Thunderstruck", "ACDC", "The Razors Edge", 5, 271.8, 320)
        song2 = Song("Thunderstruck", "ACDC", "The Razors Edge", 5, 200, 320)

        playlist.add_song(song1)
        playlist.add_song(song2)
        self.assertEqual(playlist.total_length(), 471.8)
示例#30
0
 def test_directory_extensions_4(self):
     trackList = [{
         "directory": "/home/pi/smartbot/media/recent",
         "include-subdir": True,
         "extensions": "m4a"
     }]
     p = Playlist(trackList)
     self.assertEqual(p.size(), 4)
示例#31
0
 def generate_playlist(self, playlist_name):
     output_playlist = Playlist(playlist_name)
     files = self._get_audio_files(self.__path)
     for filename in files:
         audio_obj = MP3(filename)
         song = self._create_song(audio_obj)
         output_playlist.add(song)
     return output_playlist
 def setUp(self):
     self.song = song.Song("Emerald Sword", "Rhapsody", "Fire", 4, 2400,
                           192)
     self.song2 = song.Song("Highway To Hell", "AC/DC", "Rough And Tough",
                            3, 2000, 64)
     self.my_playlist = Playlist("my_playlist")
     self.my_playlist.add_song(self.song)
     self.my_playlist.add_song(self.song2)
示例#33
0
 def test_if_total_length_return_the_same(self):
     p = Playlist(name='carl cox')
     exc = None
     k = [Song(title = 'Odin', artist = 'ManOWar',album = 'The Sons Of Odin', lenght = '3:44'),Song(title = 'Odin', artist = 'ManOWar',album = 'The Sons Of Azis', lenght = '5:44'),\
     Song(title = 'Odin', artist = 'ManOWar',album = 'The Sons Of Odin', lenght = '3:44')]
     p.add_song(k)
     res = p.total_length()
     self.assertEqual(res, '0:9:28')
示例#34
0
	def test_add_new_song_to_playlist(self):
		song1 = Song(title="Odin", artist="Manowar", album="The Sons of Odin", length="3:44")
		playlist = Playlist('my playlist')
		expected_songs_in_playlist = [song1]
	
		playlist.add_song(song1)
	
		self.assertEqual(playlist.get_songs(), expected_songs_in_playlist)	
示例#35
0
    def test_total_length(self):
        playlist = Playlist("TestPlaylist")
        song1 = Song("Thunderstruck", "ACDC", "The Razors Edge", 5, 271.8, 320)
        song2 = Song("Thunderstruck", "ACDC", "The Razors Edge", 5, 200, 320)

        playlist.add_song(song1)
        playlist.add_song(song2)
        self.assertEqual(playlist.total_length(), 471.8)
示例#36
0
 def play(self, arg=None, menuw=None):
     """
     play directory
     """
     if arg == 'next':
         Playlist.play(self, arg=arg, menuw=menuw)
     else:
         self.check_password_and_build(arg='play', menuw=menuw)
 def generate_playlist(self, playlist_name):
     output_playlist = Playlist(playlist_name)
     files = self._get_audio_files(self.__path)
     for filename in files:
         audio_obj = MP3(filename)
         song = self._create_song(audio_obj)
         output_playlist.add(song)
     return output_playlist
示例#38
0
 def test_remove_bad_quality(self):
     new_playlist = Playlist("my_playlist")
     enter_song = Song("Enter sandman", "Metallica", "Balck album", 2, 300, 192000)
     harvester_song = Song("Harvester of sorrow", "Metallica", "...And justice for all", 3, 300, 150000)
     new_playlist.songs.append(harvester_song)
     new_playlist.songs.append(enter_song)
     new_playlist.remove_bad_quality()
     self.assertEqual(len(new_playlist.songs), 1)
 def generate_playlist(self):
     result = Playlist("Rock'n'roll")
     music_files = [f for f in os.listdir(self.path) if f.endswith('.mp3') or f.endswith('.MP3')]
     for song in music_files:
         audio = MP3(self.path + "/" + song)
         print(audio)
         my_new_song = Song(audio["TIT2"], audio["TPE1"], audio["TALB"], 0, int(audio.info.length), audio.info.bitrate)
         result.add_song(my_new_song)
     return result
示例#40
0
 def generate_playlist(self, name):
     output_playlist = Playlist(name)
     files = self._get_mp3_files(self.__crawlDir)
     for filename in files:
         filename = self.__crawlDir + filename
         audio_obj = MP3(filename)
         song = self._create_song(audio_obj)
         output_playlist.add_song(song)
     return output_playlist
示例#41
0
 def generate_playlist(self):
     playlist = Playlist("myPlaylist")
     files = get_files(self.path)
     for each_file in files:
         audio = MP3('music/' + str(each_file))
         song = Song(str(audio['TIT2']), str(audio['TPE1']), str(
             audio['TALB']), 5, int(audio.info.length), audio.info.bitrate)
         playlist.add_song(song)
     return playlist
示例#42
0
    def test_save(self):
        playlist = Playlist("TestPlaylist")
        song1 = Song("Thunderstruck", "ACDC", "The Razors Edge", 5, 271.8, 320)
        song2 = Song("Thunderstruck", "ACDC", "The Razors Edge", 5, 200, 320)

        playlist.add_song(song1)
        playlist.add_song(song2)

        self.playlist.save("json.txt")
示例#43
0
    def cwd(self, arg=None, menuw=None):
        """
        make a menu item for each file in the directory
        """
        logger.log( 9, 'cwd(arg=%r, menuw=%r)', arg, menuw)
        play_items = []
        number = len(self.info['tracks'])
        if hasattr(self.info, 'mixed'):
            number -= 1

        for i in range(0, number):
            title=self.info['tracks'][i]['title']
            item = AudioItem('cdda://%d' % (i+1), self, title, scan=False)

            # XXX FIXME: set also all the other info here if AudioInfo
            # XXX will be based on mmpython
            #item.set_info('', self.name, title, i+1, self.disc_id[1], '')
            item.info = self.info['tracks'][i]
            item.length = item.info['length']
            if config.MPLAYER_ARGS.has_key('cd'):
                item.mplayer_options += (' ' + config.MPLAYER_ARGS['cd'])

            if self.devicename:
                item.mplayer_options += ' -cdrom-device %s' % self.devicename
            play_items.append(item)

        # add all playable items to the playlist of the directory
        # to play one files after the other
        self.playlist = play_items

        # all items together
        items = []

        # random playlist (only active for audio)
        if 'audio' in config.DIRECTORY_ADD_RANDOM_PLAYLIST and len(play_items) > 1:
            pl = Playlist(_('Random Playlist'), play_items, self, random=True)
            pl.autoplay = True
            items += [ pl ]

        items += play_items

        if hasattr(self.info, 'mixed'):
            d = DirItem(self.media.mountdir, self)
            d.name = _('Data files on disc')
            items.append(d)

        self.play_items = play_items

        title = self.name
        if title[0] == '[' and title[-1] == ']':
            title = self.name[1:-1]

        item_menu = menu.Menu(title, items, item_types = self.display_type)
        if menuw:
            menuw.pushmenu(item_menu)

        return items
示例#44
0
 def test_str(self):
     new_playlist = Playlist("my_playlist")
     enter_song = Song("Enter sandman", "Metallica", "Balck album", 2, 300, 192)
     harvester_song = Song("Harvester of sorrow", "Metallica", "...And justice for all",3 , 300, 150)
     new_playlist = Playlist("my_playlist")
     new_playlist.songs.append(harvester_song)
     new_playlist.songs.append(enter_song)
     expected_string = "Metallica - Harvester of sorrow 300\nMetallica - Enter sandman 300\n"
     self.assertEqual(expected_string, new_playlist.str_func())
示例#45
0
 def test_show_artists(self):
     new_playlist = Playlist("my_playlist")
     enter_song = Song("Enter sandman", "Metallica", "Balck album", 2, 300, 192)
     harvester_song = Song("Harvester of sorrow", "Metallica", "...And justice for all",3 , 300, 150)
     hells_song = Song("Hells Bells", "Ac/DC", "Back in Black",2 , 240, 256)
     new_playlist = Playlist("my_playlist")
     new_playlist.songs.append(harvester_song)
     new_playlist.songs.append(enter_song)
     new_playlist.songs.append(hells_song)
     self.assertEqual(len(new_playlist.show_artists()), 2)
示例#46
0
 def fetch_active_playlist(self):
     try:
         playlist = Playlist.get(self.active_playlist_id)
         return playlist
     except:
         # The play list have been removed or disapperd use tmpqueue as fallback
         self.active_playlist_id = self.tmpqueue_id
         self.active_playlists_track_id = 0
         playlist = Playlist.get(self.active_playlist_id)
         return playlist
示例#47
0
def main():
    path = '/home/kolchakov/Desktop/mp3/CD1/'
    crawler = MusicCrawler(path)
    songs = crawler.generate_playlist()
    my_playlist = Playlist('rock')
    my_playlist.add_songs(songs)
    while True:
        command = input("enter command>>")
        if command == "next":
            print (my_playlist.next_song())
示例#48
0
文件: to_m3u.py 项目: ekimekim/awp
def main(playlist, src, dest, scale=None, url=False):
	"""Writes the playlist in m3u format to stdout, using repetition for weight.
	src and dest args are for path rewriting - any paths under src will be rewritten
	to be under dest instead."""
	playlist = Playlist(playlist)
	flattened = playlist.to_repeated_list(scale)
	src = '{}/'.format(src.rstrip('/'))
	for path in flattened:
		if path.startswith(src):
			path = os.path.join(dest, os.path.relpath(path, src))
		print 'file://{}'.format(path) if url else path
 def test_addsong(self):
     song1 = Song("Punta", "Upsurt", "Pop Folk", 5, 3.45, 192)
     #song2 = Song("Still waiting", "Sum 41", "Qkoruda", 5, 3.20, 200)
     playlist1 = Playlist()
     playlist1.add_song(song1)
     self.assertTrue(playlist1.playlist[0].title, "Punta")
     self.assertTrue(playlist1.playlist[0].artist, "Uspurt")
     self.assertTrue(playlist1.playlist[0].album, "Pop Folk")
     self.assertTrue(playlist1.playlist[0].rating, 1)
     self.assertTrue(playlist1.playlist[0].length, 3.45)
     self.assertTrue(playlist1.playlist[0].bitrate, 192)
示例#50
0
 def generate_playlist(self, filepath):
     os.chdir(filepath)
     songs = glob.glob('*.mp3')
     playlist = Playlist("new")
     for song in songs:
         audio = MP3(song)
         song_to_add = Song(audio["TIT2"].text, audio["TPE1"].text,
         audio["TALB"].text, 0, round(audio.info.length),
         audio.info.bitrate // 1000)
         playlist.add_song(song_to_add)
     self.songs = playlist
示例#51
0
class PlaylistThreader():
	def __init__(self):
		self.playingThread = None
		self.playlist = None
		self.volume = volumizer.getJSON()['config']['milli']

	def __play_playlist(self, position = 0):
		self.setVolume(volumizer.getJSON()['config']['milli'])
		self.playlist.play(position)
		self.__oversee_playlist()

	def __oversee_playlist(self):
		while True:
			try:
				if self.playlist == None:
					break

				if self.playlist != None and self.playlist.nextTrackAvilable() and self.playlist.shouldGoNext():
					print("NEXT TRACK!")
					self.playlist.nextTrack()

				if self.playlist != None and not self.playlist.nextTrackAvilable() and self.playlist.shouldGoNext():
					print("Playlist finished playing")
					self.setPlaylist(None)
					break
			except:
				break

	def getThread(self, tracks, position = 0):
		self.playlist = Playlist(tracks, self.volume)
		self.playingThread = threading.Thread(target = self.__play_playlist, args=(position,))
		self.playingThread.daemon = True
		return {'thread' : self.playingThread,
				'playlist' : self.playlist}

	def startThread(self):
		if self.playingThread != None:
			self.playingThread.start()

	def currentPlaylist(self):
		return self.playlist

	def setPlaylist(self, playlist):
		self.playlist = playlist

	def reInit(self):
		self.playingThread = None
		self.playlist = None


	def setVolume(self, volume):
		self.volume = volume
		if self.playlist != None and self.playlist.currentTrack != None:
			self.playlist.setVolume(volume)
示例#52
0
 def test_remove_disrated(self):
     new_playlist = Playlist("my_playlist")
     enter_song = Song("Enter sandman", "Metallica", "Balck album", 2, 300, 192)
     enter_song1 = Song("Enter sandman", "Metallica", "Balck album", 2.5, 300, 192)
     harvester_song = Song("Harvester of sorrow", "Metallica", "...And justice for all",4 , 300, 150)
     new_playlist.songs.append(harvester_song)
     new_playlist.songs.append(enter_song1)
     new_playlist.songs.append(enter_song)
     new_playlist.remove_disrated(3)
     self.assertEqual(len(new_playlist.songs), 1)
     self.assertEqual(new_playlist.songs[0], harvester_song)
 def generate_playlist(self, playlist_name):
     self.collect_songs_names()
     new_playlist = Playlist("Songs in {} ".format(self.retrun_folder_name()))
     #print(os.getcwd())
     #os.chdir(self.path)
     #print(os.getcwd())
     for song_name in self.folder_files:
         file_name, file_path = MusicCrawler.split_path_and_name(song_name)
         new_playlist.list_all_songs.append(self.import_songs_from_folder(file_name, file_path))
         new_playlist.save(playlist_name)
     return new_playlist
示例#54
0
 def generate_playlist(self):
     playlist = Playlist("newList")
     os.chdir(self.path)
     for songa in glob.glob("*.mp3"):
         song = MP3(songa, ID3=EasyID3)
         try:
             playlist.add_song(Song(song.tags["title"][0], song.tags["artist"][0], "", 0, song.info.length, song.info.bitrate))
         except TypeError:
             pass
         except KeyError:
             pass
     print (playlist)
示例#55
0
class TestPlaylist(unittest.TestCase):

    def setUp(self):
        self.shell = Playlist()


#    def test_shuffle(self):
 #       self.assertEqual(self.seq, range(10))

#        self.assertRaises(TypeError, random.shuffle, (1,2,3))

    def test_do_url(self):
        track = DAAPTrack()
        self.shell.do_url(track)
        self.assertTrue(element in self.seq)
示例#56
0
 def get_playlist(self, year, month):
     play_list = None
     file_name = "{0}{1}{2:02d}{3}".format(self.file_prefix,
                                           year, month,
                                           self.file_suffix)
     full_path = os.path.join(self.base_path, file_name)
     if os.path.exists(full_path):
         play_list = Playlist()
         play_list.from_json_file(full_path)
     else:
         play_list = Playlist(source='kcrw',
                              name='%s%s' % (year, month),
                              frequency='daily')
     play_list_name = "kcrw-{0}-{1}".format(year, month)
     return (play_list, play_list_name, full_path)
 def generate_playlist(self):
     playlist = Playlist("Playlist")
     for file_name in os.listdir(self.directory):
         if fnmatch(file_name, "*.mp3"):
             self.mp3_files.append(self.directory + file_name)
             id3 = ID3(self.directory + file_name)
             mp3 = MP3(self.directory + file_name)
             song = Song(id3['TIT2'],
                         id3['TPE1'],
                         id3['TALB'],
                         5,
                         int(mp3.info.length),
                         mp3.info.bitrate)
             playlist.add_song(song)
     return playlist
示例#58
0
    def generate_playlist(self, name):
        files = os.listdir(self.music_dir)
        pl = Playlist(name)
        for f in files:
            if ".mp3" in f:
                music_file = MP3(self.music_dir+"/"+f)
                title = music_file.tags[self.TITLE][0]
                artist = music_file.tags[self.ARTIST][0]
                bitrate = music_file.info.bitrate
                length = music_file.info.length
                album = music_file.tags[self.ALBUM][0]
                temp_song = Song(title, artist, album, length, bitrate)
                pl.add_song(temp_song)

        return pl
示例#59
0
 def API_removeTrackFromPlaylist(self, playlist_id, track_id):
     try:
         playlist = Playlist.get(playlist_id)
         playlist.remove_track_id(int(track_id))
     except ValueError as e:
         raise
     self.needs_push_update = True
    def setUp(self):
        self.playlist = Playlist('DnB')
        self.come_alive = Song(
            'Come Alive',
            'Netsky',
            'Netsky-2',
            2,
            204,
            320
        )
        self.puppy = Song(
            'Puppy',
            'Netsky',
            'Netsky-2',
            4,
            280,
            96
        )
        self.horrorcane = Song(
            'Horrorcane',
            'High Rankin',
            'Unknown',
            5,
            300,
            192
        )

        self.playlist.songs = [self.come_alive, self.puppy]