def loadAllTotalItems(): songs = [] s = "" for s in os.listdir("songs/"): if s.endswith(".rtms"): sd = s[:s.index(".rtms")] songs.append(loadSong("songs/" + sd)) for s in os.listdir("songs/"): if s.endswith(".ogg"): sd = s[:s.index(".ogg")] js = song.Song(sd, "songs/" + s) ent = True for ss in songs: flog("comparando " + js.name + " con " + ss.name) if js.name == ss.name: ent = False if ent: songs.append(js) elif s.endswith(".mp3"): sd = s[:s.index(".mp3")] js = song.Song(sd, "songs/" + s) ent = True for ss in songs: if js.name == ss.name: ent = False if ent: songs.append(js) return (songs)
def test(): s1 = song.Song('Under Pressure', 'David Bowie') s1.chord_sheets[0] = ['-1', 'a', 'b', 'c', '-1'] s2 = song.Song('Under Pressure', 'Queen') s2.chord_sheets[0] = ['-1', 'a', 'b', 'c', '-1'] results = compare.run_test_suite(s1, s2, True) interface.print_results(results)
def test_total_length(self): heart_of_steel = song.Song("Heart of Steel", "Manowar", "Best", 400, 64) chandellier = song.Song("Chandellier", "Sia", "Album", 300, 128) self.good_playlist.songs.append(heart_of_steel) self.good_playlist.songs.append(chandellier) self.assertEqual(self.good_playlist.total_length(), 700)
def test_str(self): heart_of_steel = song.Song("Heart of Steel", "Manowar", "Best", 400, 64) chandellier = song.Song("Chandellier", "Sia", "Album", 300, 128) sia_song = song.Song("My Love", "Sia", "Blabla", 250, 192) self.good_playlist.songs.append(heart_of_steel) self.good_playlist.songs.append(chandellier) self.good_playlist.songs.append(sia_song)
def test_remove_bad_quality(self): heart_of_steel = song.Song("Heart of Steel", "Manowar", "Best", 400, 64) chandellier = song.Song("Chandellier", "Sia", "Album", 300, 128) self.good_playlist.songs.append(heart_of_steel) self.good_playlist.songs.append(chandellier) self.good_playlist.remove_bad_quality() self.assertFalse(heart_of_steel in self.good_playlist.songs)
def get_song(): song_info = get_song_info() output = song.Song(song_info[0], song_info[1]) while len(output.chord_sheets) == 0: print 'Song not found in our database. Please try another:' song_info = get_song_info() output = song.Song(song_info[0], song_info[1]) return output
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)
def test_remove_disrated(self): heart_of_steel = song.Song("Heart of Steel", "Manowar", "Best", 400, 64) chandellier = song.Song("Chandellier", "Sia", "Album", 300, 128) chandellier.rate(2) heart_of_steel.rate(5) self.good_playlist.songs.append(heart_of_steel) self.good_playlist.songs.append(chandellier) self.good_playlist.remove_disrated(3) self.assertFalse(chandellier in self.good_playlist.songs)
def add_song(mp): # Add an add_songs function song1 = song.Song('Welcome to the Jungle', "Guns n' Roses", 'Appetite for Destruction') song2 = song.Song('Smells Like Teen Spirit', 'Nirvana', 'Nevermind') song3 = song.Song('Jeremy', 'Pearl Jam', 'Ten') song4 = song.Song('Times Like These', 'Foo Fighters', 'One by One') song5 = song.Song('Sweet Child of Mine', "Guns n' Roses", 'Appetite for Destruction') mp.add_to_playlist(song1) mp.add_to_playlist(song2) mp.add_to_playlist(song3) mp.add_to_playlist(song4) mp.add_to_playlist(song5)
def get_billboard_songs(year, max_num_songs): interface.print_title('BILLBOARD TOP HITS') url = 'https://en.wikipedia.org/wiki/Billboard_Year-End_Hot_100_singles_of_' + str( year) response = requests.get(url) html = response.content soup = BeautifulSoup(html, "html.parser") results = soup.find('div', attrs={'id': 'mw-content-text'}).table songs = [] num = 0 for row in results.findAll('tr'): cells = row.findAll('td') if len(cells) < 2: continue title = cells[len(cells) - 2].text.replace('\"', '') artist = cells[len(cells) - 1].a.text.replace('\"', '') print '\"' + title + '\" by ' + artist + '...', ### if we change the order here, then we can use str(s)... s = song.Song(title, artist) if len(s.chord_sheets) == 0: print 'NOT FOUND' else: print 'done' songs.append(s) num += 1 if num >= max_num_songs: break return songs
def test_one(self): """Tests initialization of the song object""" self.song = Song.Song() assert self.song.getTitle() == "No title info" assert self.song.getArtist() == "No artist info" assert self.song.getAlbum() == "No album info" assert self.song.getAlbumArtist() == "No albumartist info" assert self.song.getDate() == "No date info" assert self.song.getTrackNumber() == "No tracknumber info" assert self.song.getTrackTotal() == "No tracktotal info" self.song.setTitle("Bohemian Rhapsody") self.song.setArtist("Queen") self.song.setAlbum("We Will Rock You") self.song.setAlbumArtist("Queen") self.song.setDate("1980") self.song.setTrackNumber("1") self.song.setTrackTotal("20") assert self.song.getTitle() == "Bohemian Rhapsody" assert self.song.getArtist() == "Queen" assert self.song.getAlbum() == "We Will Rock You" assert self.song.getAlbumArtist() == "Queen" assert self.song.getDate() == "1980" assert self.song.getTrackNumber() == "1" assert self.song.getTrackTotal() == "20"
def get_radio_list(state, radio_type, radio_id): # visit the radio page to get v value if 'v_val' not in state: raise Exception("visit radio page first") # get list of songs radio_list_url = radio_list_url_temp % (radio_type, radio_id, state['v_val']) logger.debug("radio list: %s" % radio_list_url) radio_list = urllib2.urlopen(radio_list_url).read() # parse list try: root = ET.fromstring(radio_list) except Exception as e: logger.error("fail to parse song list!") logger.error(radio_list) raise e tracks = [] for child in root: if child.tag == 'config': # update personal info from new data info.update_state(state, child) elif child.tag == 'trackList': for track_node in child: track = song.Song() for prop_node in track_node: tag = prop_node.tag text = prop_node.text if tag == 'location': text = song.decrypt_location(text) setattr(track, tag, text) tracks += [track] return tracks
def random_song(root, legal_pitches, scale, num_phrases=3, phrase_length=4, num_verses=2, verse_length=2, tempo=80, num_mutations=0): test_song = song.Song(root=root, tempo=tempo, legal_pitches=legal_pitches) chords = [song.Chord(root, scale, test_song) for _ in range(phrase_length)] [chord.initialize_note_seq(default=REST) for chord in chords] phrase = song.Phrase(chords, test_song) chord_phrases = [phrase for _ in range(num_phrases)] verse = song.Verse(chord_phrases, test_song) verses = [verse for _ in range(num_verses)] test_song.add_verses(verses) for _ in range(num_mutations): test_song.recursive_mutate() return test_song
def getSongs(query, playlistid=""): con = connect() cur = con.cursor() query = '%' + query + '%' if playlistid == "": cur.execute( 'SELECT id, title, artist, length, path FROM songs WHERE title LIKE %s', (query, )) else: cur.execute( 'SELECT id, title, artist, length, path FROM songs WHERE title LIKE %s AND id IN (SELECT songid FROM contains WHERE playlistID=%s)', (query, playlistid)) songs = [] for row in cur.fetchall(): minutes = row[3] / 60 seconds = row[3] % 60 length = str(minutes) + ':' + ('0' if seconds < 10 else '') + str(seconds) songs.append(song.Song(row[0], row[1], row[2], length, row[4])) return songs
def get_songs(self): import song import band conn = sqlite3.connect('db/musicaly.db') s = conn.execute( """SELECT id FROM Song WHERE ARTIST_TYPE ='Artist' AND (ARTIST_ID=? OR FT_ID=?)""", ( self.id, self.id, )) songs_id = s.fetchall() songs = [] for i in songs_id: new_song = song.Song() new_song.load(i[0]) songs.append(new_song) s = conn.execute( """SELECT BAND_ID FROM Band_Artist WHERE ARTIST_ID=?""", (self.id, )) bands_id = s.fetchall() if len(bands_id) > 0: for i in bands_id: band = band.Band(i[0]) sgs = band.get_songs() songs = songs + sgs return songs
def test_simple_song(self): self.assertPrints( song_ast.Song( title="Hello, world", subtitle="One of the great timeless classics", children=[ song_ast.Verse([ song_ast.Line([(None, "Hello, "), ("Bb", "world!")]), song_ast.Line([(None, "Hello, "), ("Bb", "world!")]), ]), song_ast.Chorus([ song_ast.Line([(None, "Hello, "), ("Bb", "world!")]), song_ast.Line([(None, "Hello, "), ("Bb", "world!")]), ]), ] ), "\n".join([ "Hello, world", "One of the great timeless classics", "=" * 79, "", "Hello, [Bb]world!", "Hello, [Bb]world!", "", "- Chorus -", "Hello, [Bb]world!", "Hello, [Bb]world!", ]) + "\n" )
def menu(): option = "" print ("bienvenido a la primera verción de ritmsounds! \n Veamos si eres capaz de seguir el ritmo sólo oyendo las indicaciones") juego.resultsEvent+=desplegarResultados while (option != "0"): print ("menú principal: ¿qué deseas hacer? \n escribe 0 para salir \n escribe 1 para probar las teclas y conocer los sonidos asociados \n 2 para jugar una canción \n 3 para grabar tu propia secuencia de pasos para una canción") option = input() if option == "1": testkeysWindow.startWindow(screen_width, screen_height) elif option == "2": print("ingrese el nombre de la canción a la cual desea jugar, incluya la extención \n recuerde que la canción para ser jugable tiene que tener un archivo rtms creado previamente!") cancion = input() if os.path.isfile(songs_dir + cancion) == False or os.path.isfile(songs_dir+cancion+".rtms") == False: print("no existe esa cancion \n o no posee un archivo rtms creado.") else: print("preciona enter para iniciar a jugar \n ¡danse danse!") input() j = escritor.loadSong(songs_dir+cancion) j.selectSteplist(0) playWindow.startWindow(screen_width,screen_height,j) elif option == "3": print("ingrese el nombre completo de la canción a la cual crearle los pasos. \n recuerde que la canción debe de estar en la carpeta songs/ y tiene que escribir el nombre incluyendo la extención") cancion = input() if os.path.isfile(songs_dir + cancion) == False: print("no existe esa cancion") else: print("preciona enter para iniciar la grabación") input() j = song.Song(cancion,songs_dir+cancion) recordWindow.startWindow(screen_width,screen_height,j)
def __init__(self, width, height, title): super().__init__(width, height, title) # Call the parent class's init function self.song = song.Song() self.listOfKeys = [] for i in range(1, 4): self.listOfKeys.append(key.Key(i))
def read_items(self, buckets=None, results=15, start=0, item_ids=None): """ Returns data from the catalog; also expanded for the requested buckets Args: Kwargs: buckets (list): A list of strings specifying which buckets to retrieve results (int): An integer number of results to return start (int): An integer starting value for the result set Returns: A list of objects in the catalog; list contains additional attributes 'start' and 'total' Example: >>> c <catalog - my_songs> >>> c.read_items(results=1) [<song - Harmonice Mundi II>] >>> """ kwargs = {} kwargs['bucket'] = buckets or [] kwargs['item_id'] = item_ids or [] response = self.get_attribute("read", results=results, start=start, **kwargs) rval = ResultList([]) if item_ids: rval.start = 0 rval.total = len(response['catalog']['items']) else: rval.start = response['catalog']['start'] rval.total = response['catalog']['total'] for item in response['catalog']['items']: new_item = None # song items if 'song_id' in item: item['id'] = item.pop('song_id') item['title'] = item.pop('song_name') request = item['request'] new_item = song.Song(**util.fix(item)) new_item.request = request # artist item elif 'artist_id' in item: item['id'] = item.pop('artist_id') item['name'] = item.pop('artist_name') request = item['request'] new_item = artist.Artist(**util.fix(item)) new_item.request = request # unresolved item else: new_item = item rval.append(new_item) return rval
def __init__(self, parsed, id_, type_): self.type = parsed['type'] self.last_song_id = parsed['lastSongId'] self.tracks = [] for track in parsed['trackList']: self.tracks.append(song.Song(track)) self.playlist_id = id_ self.playlist_type = type_
def load_directory(self, directory): directory_ = os.path.abspath(directory) if directory_ in self.directories: return # Don't add the same directory twice logger.info('Loading directory ' + directory + '...') self.directories.append(directory_) self.songs.extend([song.Song(os.path.join(directory_, f)) for f in os.listdir(directory_) if os.path.isfile(os.path.join(directory_, f)) and (f.endswith('.wav') or f.endswith('.mp3'))]) self.init_key_title_map()
def to_ast(infile): lines = [_chordpro_line(line) for line in infile.readlines()] keys_and_values = dict(lines) title = keys_and_values.get("title", "").strip() subtitle = keys_and_values.get("subtitle", "").strip() chords = {} children = _convert_lines_to_ast_nodes(iter(lines), chords=chords) return song.Song(children, title=title, subtitle=subtitle, chords=chords)
def search_song(song_request): object_storage = {} for i in range(0, 26, 2): #Checks whether cell's (A1, C1, E1.....) has users if worksheet.acell(letters[i] + "1").value == "": break else: #Loops down that row for j in range(2, 998): string_j = str(j) #Checks whether cell's (A#. C#, E#....) has the users song requested stored inside if worksheet.acell(letters[i] + string_j).value == "": break else: #Appends to the object_storage dictionary with {songname/artistname : lyrics} object_storage.update({ worksheet.acell(letters[i] + str(j)).value: worksheet.acell(letters[i + 1] + str(j)).value }) #Converts the key and value into an object song_object = [] for key in object_storage: #Creates an instance of the Song Object(Songname, lyrics) objects = song.Song(key, object_storage[key]) song_object.append(objects) #Creating User Objects with parameters (userID, an instance of a song object) user_storage = {} for i in range(0, 26, 2): if worksheet.acell(letters[i] + "1").value == "": break else: for j in range(0, len(song_object)): #Make a dictionary {songname, user_id}, since keys must have unique values user_storage.update( {song_object[j]: worksheet.acell(letters[i] + "1").value}) user_object = [] for key in user_storage: #Creates an instance of the User Object(UserID, Song Object) objects = user.User(user_storage[key], key) user_object.append(objects) #Objective: #Since the lyrics are next to the title #Search for the song_requested from the user inside the spreadsheet, return #Column + 1 #Only Need to search through Column's A,C,E..... #Going through Each Column for i in range(0, len(song_object)): #If the song has been requested previously, then loop through the user, song song object to find the stored lyrics if song_object[i].songname() == song_request: return song_object[i].songlyrics() break else: #Not requested before, obtain the lyrics by making the API call return lyric_print(song_request) break
def findSongs(self): """Searches musicFilesLocation for music files, then puts it in Songs list""" if self.musicFilesLocation == "": self.setMusicFilesLocationFromUserInput() # raise IOError musicFileExtensions = [ '.3gp', '.aa', '.aac', '.aax', '.act', '.aiff', '.amr', '.ape', '.au', '.awb', '.dct', '.dss', '.dvf', '.flac', '.gsm', '.iklax', '.ivs', '.m4a', '.m4b', '.m4p', '.mmf', '.mp3', '.mpc', '.msv', '.ogg', '.oga', '.mogg', '.opus', '.ra', '.rm', '.raw', '.sln', '.tta', '.vox', '.wav', '.wma', '.wv', '.webm' ] for thing in os.walk(self.musicFilesLocation): for ext in musicFileExtensions: # thing is tuple: (pathname, dirs, files) # we want the files. os.walk then recurses into any dirs, so we catch files in there too for possibleMusicFile in thing[2]: if ext in possibleMusicFile: newSong = Song.Song() metadata = mutagen.File(thing[0] + "/" + possibleMusicFile) newSong.setFileName(possibleMusicFile) newSong.setFileLocation( thing[0] + "/") #self.musicFilesLocation + "/") newSong.getSongInfoFromFile() # try: # newSong.setTitle(metadata["title"][0]) # except KeyError as e: # print(e) # try: # newSong.setArtist(metadata["artist"][0]) # except KeyError as e: # print(e) # try: # newSong.setAlbum(metadata["album"][0]) # except KeyError as e: # print(e) # try: # newSong.setAlbumArtist(metadata["albumartist"][0]) # except KeyError as e: # print(e) # try: # newSong.setDate(metadata["date"][0]) # except KeyError as e: # print(e) # try: # newSong.setTrackNumber(metadata["tracknumber"][0]) # except KeyError as e: # print(e) # try: # newSong.setTrackTotal(metadata["tracktotal"][0]) # except KeyError as e: # print(e) self.Songs.append(newSong)
def get_white_noise_songs(self): da = db_operation.Db('fm.db') recom_tem = da.get_songs_by_label("白噪音") song1 = song.Song() recom_ans = [] for i in range(len(recom_tem)): song1 = song.Song() song1.set_songid(recom_tem[i]) song1.get_details_from_songid() song_info = {} song_info["label"] = song1.label song_info["singer"] = song1.singer song_info["songurl"] = song1.songurl song_info["picurl"] = song1.picurl song_info["lrcurl"] = song1.lrcurl song_info["name"] = song1.name song_info["songid"] = song1.songid recom_ans.append(song_info) recom_ans = random.sample(recom_ans,50) return recom_ans
def main(): global seed melody = song.Song() remove_files(force=True) if (INSTRUMENT is None): ip = instrumentPicker.InstrumentPicker(SOUNDFONT_PATH) melody.instrument = ip.Pick() else: melody.instrument = INSTRUMENT if (TEMPO is None): tl = randomList() tl.add(tempos, recursive=True) melody.tempo = tl.pickNormal() else: melody.tempo = TEMPO if (KEY is None): melody.key = random.choice(keys.major_keys) else: melody.key = KEY if (SEED is None): seed = random.randrange(sys.maxsize) print("Seed was: " + str(seed)) random.seed(seed) else: seed = SEED print("Seed supplied: " + str(SEED)) random.seed(seed) print(melody.tempo) print(melody.instrument) print(melody.key) melody.notes = write_song(melody) create_sheet(melody) create_frames(melody) exportToWav(melody) message = 'Instrument: ' + melody.instrument + ' \nTempo: ' + str( melody.tempo) + '\nPlayed in the key of ' + melody.key + '.' print(message) wavToMp4() upload_song(melody) if (ARCHIVE_FILES): archive_files(FILE_HOME, ARCHIVE_LOCATION) remove_files() #Finally, we exit return
def user_song(user_id): object_storage = {} for i in range(0, 26, 2): #Checks whether cell's (A1, C1, E1.....) has users if worksheet.acell(letters[i] + "1").value == "": break else: #Loops down that row for j in range(2, 998): string_j = str(j) #Checks whether cell's (A#. C#, E#....) has the users song requested stored inside if worksheet.acell(letters[i] + string_j).value == "": break else: #Appends to the object_storage dictionary with {songname/artistname : lyrics} object_storage.update({ worksheet.acell(letters[i] + str(j)).value: worksheet.acell(letters[i + 1] + str(j)).value }) #Converts the key and value into an object song_object = [] for key in object_storage: #Creates an instance of the Song Object(Songname, lyrics) objects = song.Song(key, object_storage[key]) song_object.append(objects) #Creating User Objects with parameters (userID, an instance of a song object) user_storage = {} for i in range(0, 26, 2): if worksheet.acell(letters[i] + "1").value == "": break else: for j in range(0, len(song_object)): #Make a dictionary {songname, user_id}, since keys must have unique values user_storage.update( {song_object[j]: worksheet.acell(letters[i] + "1").value}) user_object = [] for key in user_storage: #Creates an instance of the User Object(UserID, Song Object) objects = user.User(user_storage[key], key) user_object.append(objects) song_list = "" #Check whether the sender_id is inside the user_object if len(user_object) == 0: return "You have not requested any songs from here" else: for i in range(0, len(user_object)): if user_object[i].senderid() == user_id: song_list = song_list + "\n" + user_object[i].song().songname() return song_list
def get_songs(self): import song conn = sqlite3.connect('db/musicaly.db') s = conn.execute( """SELECT SONG_ID FROM Genre_Song where GENRE_ID = ?""", (self.id, )) songs_id = s.fetchall() songs = [] for i in songs_id: new_song = song.Song() new_song.load(i[0]) songs.append(new_song) return songs
def get_songs(self): #推荐约80首歌 user_song = self.load_matrix(); recom_list = self.get_recommendation(user_song,self.uid) #针对当前用户生成协同过滤推荐列表 label_list, singer_list, rand_list=self.get_recommendations() recom_list=[l[1] for l in recom_list if l[0] != 0] if len(recom_list) >=30: recom_list=random.sample(recom_list,30) recom_tem = list(set(recom_list+label_list+singer_list+rand_list)) song1 = song.Song() recom_ans = [] for i in range(len(recom_tem)): song1 = song.Song() song1.set_songid(recom_tem[i]) song1.get_details_from_songid() song_info = {} song_info["label"] = song1.label song_info["singer"] = song1.singer song_info["songurl"] = song1.songurl song_info["picurl"] = song1.picurl song_info["lrcurl"] = song1.lrcurl song_info["name"] = song1.name song_info["songid"] = song1.songid recom_ans.append(song_info) return recom_ans
def getSong(songid): con = connect() cur = con.cursor() cur.execute( 'SELECT id, title, artist, length, path FROM songs WHERE id=%s', (songid, )) songtuple = cur.fetchone() seconds = songtuple[3] % 60 minutes = songtuple[3] / 60 length = str(minutes) + ':' + ('0' if seconds < 10 else '') + str(seconds) return song.Song(songtuple[0], songtuple[1], songtuple[2], length, songtuple[4])