Exemplo n.º 1
0
 def clickAddQue(self, listbox1, listbox2):
     queueSongTitle = listbox1.get(listbox1.curselection())
     if queueSongTitle == None:
         #upon startup, the default song is the first song
         queueSong = Song.Song()
     else:
         #recreate song object from selected song title in listbox
         queueSongPath = self.mp3_object.getPath() + "/" + queueSongTitle
         queueSong = Song.Song(queueSongPath)
         self.mp3_object.addToQueue(queueSong)
         listbox2.insert(listbox2.size(), queueSong.getTitle())
Exemplo n.º 2
0
    def importPlaylist(self):
        path, dir, mp3files = next(os.walk(self.path))
        self.files = mp3files
        self.path = path

        #create song objects for each mp3 file found. Store in MusicLibrary
        for mp3 in self.files:
            mp3path = self.path + "/" + mp3
            newSong = Song.Song(mp3path)
            self.musicDictionary[newSong] = newSong.getPath()

        # #order songs in alphabetical order in musiclibrary
        # h = 0
        # while h < len(self.musicLibrary):
        #     i = 0
        #     while i < len(self.musicLibrary) - 1:
        #         firstSong = self.musicLibrary[i]
        #         secSong = self.musicLibrary[i + 1]
        #         #compare titles
        #         j = 0
        #         while j < len(secSong.getTitle()): #always comparing against the shortest song name
        #             if secSong.getTitle()[j] < firstSong.getTitle()[j]: #if the second song comes first
        #                 self.musicLibrary[i] = secSong
        #                 self.musicLibrary[i + 1] = firstSong
        #                 i += 1
        #                 j = len(secSong.getTitle()) #break out of for loop
        #             elif secSong.getTitle()[j] > firstSong.getTitle()[j]: #if first song comes first
        #                 i += 1
        #                 j = len(secSong.getTitle())
        #             elif secSong.getTitle()[j] == firstSong.getTitle()[j]:
        #                 j += 1
        #     h += 1

        #set first song as currentSong by default
        self.currentSong = list(self.musicDictionary.keys())[0]
Exemplo n.º 3
0
def snippet_analyzer(snippet):
    ''' This function analyzes the snippet signal and find
    the match in the song library

    Keyword Argument:

    snippet_signal -- A dictionary with fields including
    signal, name, sampling_rate, and audio_source
    '''
    snippet_signal = snippet['audio_signal']
    snippet_name = snippet['audio_name']
    sampling_rate = snippet['sampling_rate']
    snippet_address = snippet['audio_source']
    # Construct a Song Object called snippet_song
    snippet_song = Song.Song(snippet_signal, title_info=snippet_name,
                             address_info=snippet_address,
                             sampling_rate_info=sampling_rate)
    # Use the signature of the snippet to find match in the
    # song library
    matched_song, matched_time, params_cp, T, acy_level = signature_match(
        snippet_song.signature)
    # Return the matching information
    print(f"""The snippet matches with the song with title
         {matched_song[1]}, created by {matched_song[2]}""")
    print(f"""The recording has a sampling rate of {int(matched_song[3])}
          and lasts {round(float(matched_song[4]), 1)} seconds""")
    print(f"""The snippet matches with {matched_song[1]}
          at as early as {float(min(matched_time))} seconds""")
    K = params_cp.k
    L = params_cp.l
    lsh_family = str(params_cp.lsh_family)
    print(f"""Use {K} {lsh_family} function and {L} hash tables,
         {T} probes for approximate NN search.""")
Exemplo n.º 4
0
    def __init__(self, skrn, musicPlayer):
        self.skrn = skrn
        self.musicPlayer = musicPlayer
        self.topLeft = (225, 75)
        self.topRight = (525, 75)
        self.botRight = (575, 125)
        self.botLeft = (275, 125)

        songs = [Song(f) for f in os.listdir(CWD + '/Media/Music/')]
        self.albumManager = AlbumManager(songs)
        self.musicPlayer.playPlaylist(self.albumManager.albums[0])
        self.albumButtons = []
        self.buttonHeight = 25
        self.buttonYOffset = 25

        self.scrolling = False
        self.scrollOffset = 0

        for x in range(len(self.albumManager.albums)):
            p1 = (self.botLeft[0], 100 + self.buttonYOffset + (1+x)*self.buttonHeight + 10*x)
            p2 = (self.topRight[0], 100 + self.buttonYOffset + (1+x)*self.buttonHeight + 10*x)
            p3 = (self.botRight[0]-1, 125 + self.buttonYOffset + (1+x)*self.buttonHeight + 10*x)
            p4 = (self.botLeft[0], 125 + self.buttonYOffset + (1+x)*self.buttonHeight + 10*x)
            self.albumButtons.append(AlbumButton(self.skrn, self, self.albumManager.getAlbum(x).name, (p1, p2, p3, p4), self.setAlbum, x))
        self.yOffset = SmartValue(-150 - (self.buttonHeight+self.buttonYOffset)*len(self.albumButtons))
        self.points = self.getPoints()
        self.animateState = -1
        print(self.albumManager.albums[0].getLength())
Exemplo n.º 5
0
async def enqueue(ctx):
    global playqueue
    split = ctx.message.content.split(" ")
    link = split[1]
    music = Song.Song(link, ctx.message.channel, ctx.message.author)
    await displayembed("Enqueue", ctx)
    playqueue.append(music)
    return
Exemplo n.º 6
0
 def loadPlaylist(self):
     playlistFile = open(MEDIA_PATH + 'Playlists/' + self.name, 'r')
     lines = playlistFile.read().split('\n')
     playlistFile.close()
     for line in lines:
         if len(line) < 2:
             break
         self.songs.append(Song(line))
     self.size = len(self.songs)
Exemplo n.º 7
0
    def __init__(self, pin=NO_PIN, song=None):
        self.isRecording = False
        self.song = Song.Song() if song is None else song

        self.pin = pin
        if (self.pin != KeyRecord.NO_PIN):
            GPIO.setmode(GPIO.BCM)
            GPIO.setwarnings(False)
            GPIO.setup(pin, GPIO.OUT)
Exemplo n.º 8
0
def slowSearch(snippet):
    ''' This function takes a snippet
    searches throuh the library by comparing the local
    periodograms without a special signature.

    Keyword argument:
    snippet -- A given snippet, coming from the IO module
    with the given information about signal, sampling_rate,

    '''
    # Obtain the size of the snippet
    snippet_signal = snippet['audio_signal']
    snippet_name = snippet['audio_name']
    sampling_rate = snippet['sampling_rate']
    snippet_address = snippet['audio_source']
    # Construct a Song Object called snippet_song
    snippet_song = Song.Song(snippet_signal, title_info=snippet_name,
                             address_info=snippet_address,
                             sampling_rate_info=sampling_rate)
    snippet_spectra = snippet_song.get_spectrogram()
    # Deserialize song_lib and search through periodograms in
    # song_lib
    with open('song_lib.pickle', 'rb') as handle:
        song_lib = pickle.load(handle)

    # Search through the whole library and compare the snippet
    # with every song.
    for song in song_lib:
        # Get the song's spectrogram
        hf = h5py.File(song_lib[song]['h5_address'], 'r')
        song_spectra = hf['spectrogram'][()]
        hf.close()
        # Compare the song's spectrogram with the snippet's
        # spectrogram
        for i in range(snippet_spectra.shape[1]-6):
            for j in range(song_spectra.shape[1]-6):
                # Calculate the cosine similarity between local periodogram
                initial_similarity = 1 - spatial.distance.cosine(
                                         snippet_spectra[:, i],
                                         song_spectra[:, j])
                # If the similarity is bigger than 75%, then we will search
                # through the successive window and determine if we had a match
                if initial_similarity >= .75:
                    successive_similarity = [spatial.distance.cosine(
                                             snippet_spectra[:, i+k],
                                             song_spectra[:, j+k])
                                             for k in range(1, 6)]
                    successive_similarity = [1 - s for s in
                                             successive_similarity]
                    if min(successive_similarity) >= 0.7:
                        # matching_rslt = 'The snippet finds a match!'
                        print("""The snippet finds a match!.
                                 The matching song is: \n""")
                        print(song)
                        return(library_read(song))
    print("The snippet doesn't find a match in the library.")
Exemplo n.º 9
0
def Add(song, title=None, artist_info=None):
    song = IO.audio_to_signal(song)
    if title is None:
        title = song['audio_name']
    song = Song.Song(song['audio_signal'],
                     sampling_rate_info=song['sampling_rate'],
                     address_info=song['audio_source'],
                     title_info=title,
                     artist_info=artist_info)
    DbManager.library_add(song)
Exemplo n.º 10
0
 def getSong(self, songName):
     try:
         for song in self.allSongs:
             if (song.getName() == songName):
                 print("Song already imported.")
                 return 1
         self.allSongs.append(Song(songName))
         return 0
     except:
         return 1
Exemplo n.º 11
0
 def populateFromDirectory(self):
     self.songs = []
     self.songCount = 0
     for root, dirs, files in os.walk(self.musicDirectory):
         for element in files:
             if element.endswith(MP3):
                 self.songCount = self.songCount + 1
                 mp3Index = len(element) - len(MP3)
                 name = element[:mp3Index]
                 slashIndex = len(self.musicDirectory) + len(SLASH)
                 path = root[slashIndex:] + SLASH
                 self.songs.append(Song(name, path))
Exemplo n.º 12
0
async def enqueue(ctx):
    global playqueue
    try:
        split = ctx.message.content.split(" ")
        split = split[1]
        split = split.split("&")
        link = split[0]
        music = Song.Song(link, ctx.message.channel, ctx.message.author)
        await displayembed("Enqueue",ctx)
        playqueue.append(music)
    except Exception as e:  
        await write_errors("Exception occured in enqueue: {0} at {1}".format(e, str(datetime.now())))
    return
Exemplo n.º 13
0
def scan_songs(path):
    songs = []
    for root, directories, filenames in os.walk(path):
        for filename in filenames:
            path = os.path.join(root, filename)
            tag = id3.Tag()
            tag.parse(path)
            album = tag.album
            artist = tag.artist
            title = tag.title
            genre = tag.genre
            song = Song(title, path, artist, album, genre)
            songs.append(song)
    return songs
Exemplo n.º 14
0
	def loadSongs(self):
		s = []
		sList = []
		f = open("Song_Info.txt",'r')
		lines = f.readlines()
		for line in lines:
			info = line.split("$")
			if len(info) != 6:
				print "[!] Corrupted Song_Info file! You may want to recreate the file with the command \"restore\""
				continue
			info[len(info)-1] = info[len(info)-1].split(":")
			sList.append(info[0].lower())
			s.append(Song(info[3],info[1],info[0],info[2],info[5],info[4]))
		return s,sList
Exemplo n.º 15
0
    def clickPlay(self, listbox1):

        #play a song if something is selected in the listbox
        try:
            if listbox1.get(listbox1.curselection()) != "":
                selectedSongTitle = listbox1.get(listbox1.curselection())
                selectedSongPath = self.mp3_object.getPath(
                ) + "/" + selectedSongTitle
                selectedSong = Song.Song(selectedSongPath)
                self.mp3_object.normalPlay(selectedSong)
        #will throw error if nothing is selected. If this happens, play normal
        except:
            firstSong = self.mp3_object.getMusicLibrary()[0]
            self.mp3_object.normalPlay(firstSong)
Exemplo n.º 16
0
    def populateFromFile(self):
        self.songs = []
        self.songCount = 0

        fileObj = FileHandler(self.directory, "Songs")
        fileString = fileObj.read()
        tokenizer = StringTokenizer(NEWLINE)
        tokenizer.setString(fileString)
        while not tokenizer.atEnd():
            self.songCount = self.songCount + 1
            token = tokenizer.getToken()
            index = token.index("/,")
            name = token[index + 2:]
            path = token[:index + 1]
            self.songs.append(Song(name, path))
def getSongs_MSD(MSD_data_folder_path):
    rootdir = MSD_data_folder_path
    song_list = []
    count = 0
    for subdir, dirs, files in os.walk(rootdir):
        for file in files:
            filepath = subdir + os.sep + file
            if filepath.endswith(".h5"):
                f = h5.File(filepath, "r")
                songDict = getSongAttributes_MSD(f)
                song = Song.Song(songDict)
                song_list.append(song)
                count += 1
                if count % 500 == 0:
                    print "processed %d songs..." % count
    print "Successfully extracted %d songs." % count
    return song_list
Exemplo n.º 18
0
 def add_song(self, a_song):
     #if a_song is an instance of the Song class, just append it to the
     #list
     if isinstance(a_song, Song):
         #The song should have the name of the CD as the name of the album
         if a_song.get_album() == self._album:
             self._songs.append(a_song)
         #If the song doesn't have the same title, it doesn't belong
         else:
             raise Exception(a_song.get_title() + " is not on " +
                             self._album + " album.")
     #if a_song is just a song title, create an instance of the Song
     #class and set the title.  Leave the other fields blank
     else:
         new_song = Song()
         new_song.set_title(a_song)
     return
Exemplo n.º 19
0
  def scrape_songs(self, page_num=0):
    song_list = []
    url = self.url + str(page_num) + "/"
    response = get(url, timeout=5)
    content = BeautifulSoup(response.content, "html.parser")

    # Loop for each song on the current page
    for song in content.findAll("div", {"class" : "grid-item song"}):
      throwback = False
      song_name = song.find("a", {"class" : "cover-title grid-item-title"}).text.strip()

      # May be a song made by a group of artists
      for group in song.findAll("div", {"class" : "grid-item-artists"}):
        artists = group.findAll("em", {"class" : "default-artist"})
        main_artists = "".join([individual.text.strip() + " " for individual in artists]).strip()

        # Extract feature artist(s) if any
        features_list = []
        for feature in group.findAll("em", {"class" : "no-bold"}):
          if feature not in self.excluded:
            features_list.append(feature.text.strip()) 
        features_string = ", ".join(features_list)

      # Extract the release date of the song & find out if this is a throwback
      for meta_data in song.findAll("div", {"class" : "grid-item-meta-info hidden-md-down"}):
        for tag in meta_data.findAll("span", {"class" : "song-review"}):
          if (tag.text == "THROWBACK"):
            throwback = True
        for time in meta_data.findAll("span", {"class" : "grid-item-time song pull-right"}):
          release_date = self.format_date(time.findAll("span")[0].text.strip())

      # Extract the link to the song page
      prefix = "https://www.hotnewhiphop.com"
      for link in song.findAll("a", {"class" : "cover-title grid-item-title"}, href=True):
        song_page = prefix + link["href"]
      
      # Append to song list
      if (not throwback):
        song_list.append(Song(song_name, main_artists, features_string, release_date, song_page, features_list))
      else:
        print("Throwback:\t {} : {} : {}".format(main_artists, song_name, song_page))

    # Return list of Song objects
    return song_list
 def import_From_Playlist(self, playlist):
     songs = []
     for i in range(0, len(playlist.playlist_song_names)):
         song_attributes = {
             "accousticness": playlist.playlist_accousticness[i],
             "artist_name": playlist.playlist_song_artists[i],
             "cluster_id":
             9999,  # cluster_id = 9999 indicates not clustered
             "danceability": playlist.playlist_dancibility[i],
             "energy": playlist.playlist_energy[i],
             "from_playlist": playlist.playlist_playlistname,
             "instrumentalness": playlist.playlist_instrumentalness[i],
             "loudness": playlist.playlist_loudness[i],
             "speechiness": playlist.playlist_speechness[i],
             "tempo": playlist.playlist_tempo[i],
             "title": playlist.playlist_song_names[i],
             "valence": playlist.playlist_valence[i]
         }
         song = Song(song_attributes)
         songs.append(song)
     self.insert_Songs(songs)
Exemplo n.º 21
0
 def load_songs(self):
     self.song_list.append(Song.Song(1, "Music/Tango/Santa Maria.mp3", 118))
Exemplo n.º 22
0
        print("Records sorted by composer:")
        keyfun = lambda record: record.composer_name
        self.records.sort(key=keyfun)
        for record in self.records:
            print("'" + record.record_name + "'" + " by " + "'" +
                  record.composer_name + "'" + ";")

    # def switch(self):
    # switcher = {1: "Please type the genre", 2: "", 3: ""}
    # print (switcher.get(self, "Invalid value"))


if __name__ == '__main__':
    store = Music_Store()
    hurt = Song(record_genre.ROCK, "Nine Inch Nails", "Industrial",
                "Alan Moulder", "Hurt", "The Downward Spiral", 1994, 2.49, 375,
                1993, 15, "Trent Reznor")
    ziggy = Song(record_genre.ROCK, "David Bowie", "Glam rock", "Ken Scott",
                 "Ziggy Stardust", "Ziggy Stardust and the Spiders from Mars",
                 1973, 2, 201, 1972, 4, "David Bowie")
    smooth_criminal = Song(record_genre.POP, "Michael Jackson", "Funk",
                           "Quincy Jones", "Smooth Criminal", "Bad", 1987, 1.5,
                           257, 1985, 1, "Michael Jackson")
    symphony_9 = Song(record_genre.CLASSIC, "Hamburg orchestra", "Symphony",
                      "None", "Symphony No. 9", "Baloon Concerto", 1979, 4,
                      1023, 1822, 4, "Ludwig van Beethoven")
    hand_covers_bruise = Song(record_genre.SOUNDTRACK,
                              "Trent Reznor and Atticus Ross", "Dark ambient",
                              "Trent Reznor and Atticus Ross",
                              "Hand Covers Bruise", "The Social Network", 2010,
                              5, 603, 2010, 1, "Trent Reznor and Atticus Ross")
Exemplo n.º 23
0
def parse_data(result):
    data = result['tracks']['items']

    for item in data:

        track_id = item['id']

        artist_id = item['album']['artists'][0]['id']
        artist_details = spotify.artist(artist_id)

        album_tracks = spotify.album_tracks(item['album']['id'])
        album_track = []

        album_recommendations = []

        recommendations = spotify.recommendations(
            seed_tracks=["{}".format(track_id)], limit=4)
        for r in recommendations['tracks']:
            album_recommendations.append({
                "album_art":
                r['album']['images'][0]['url'],
                "album_name":
                r['album']['name'],
                "name":
                r['name'],
                "url":
                r['external_urls']['spotify']
            })

        for tracks in album_tracks['items']:
            album_track.append({
                "name": tracks['name'],
                "url": tracks['external_urls']['spotify']
            })

        artist = {
            "image": artist_details['images'][1]['url'],
            "name": artist_details['name']
        }

        album = {
            "name": item['album']['name'],
            "art": item['album']['images'][1]['url'],
            "tracks": album_track,
            "recommendations": album_recommendations
        }

        track = {
            "name": item['name'],
            "url": item['external_urls']['spotify'],
            'popularity': item['popularity'],
            "id": track_id
        }

        lyrics = get_lyrics.get_lyrics(track['name'], artist['name'])

    track_details = Song.Song(artist_name=artist['name'],
                              artist_image=artist['image'],
                              album_name=album['name'],
                              album_art=album['art'],
                              album_tracks=album['tracks'],
                              track_name=track['name'],
                              url=track['url'],
                              popularity=track['popularity'],
                              id=track['id'],
                              recommendations=album['recommendations'],
                              lyrics=lyrics)

    return track_details
Exemplo n.º 24
0
shutil.copytree(scripts, build_scripts)
shutil.copytree(css, build_css)
shutil.copytree(images, build_images)

#run certain scripts through the template process while copying
with open(build_scripts + 'abs.js', 'w') as target:
    with open(abs_js_templ, 'r') as templ:
        target.write(templ.read().replace('SITEROOT', siteroot))

# populate the songs and albums lists, copy the song files, and generate album artwork

#pull metadata from mp3s, building the songs data structure, and copy them to the media directory
for song in os.listdir(songfiles):
    if song.endswith('.mp3'):
        #get metadata from mp3 files
        s = Song(song, File(songfiles + song))
        songs.append(s)
        #copy song file to site, sanitizing filename, but only if the files differ
        try:
            if not filecmp.cmp(songfiles + song, build_media + s.filename):
                shutil.copyfile(songfiles + song, build_media + s.filename)
                changed_albums.add(s.albumname)
        except:  # assume failed because the filecmp failed because the file wasn't in the build directory already, so just copy it
            shutil.copyfile(songfiles + song, build_media + s.filename)

# remove any songs still in media that are no longer in the songfiles directory
# build a set of songs in the songfiles directory
current_songs = set([])
for song in songs:
    current_songs.add(safe(song.filename))
Exemplo n.º 25
0
import sys
sys.path.insert(1, '/home/benjamin/CS/Python/mp3_builder/src')
import Song as Song
#Test cases for Song.py

#does it properly create a Song object
# song1 = Song.Song("file/to/mp3/my_favorite_song.mp3")
song1 = Song.Song("/home/benjamin/Music/38 Special- Caught up in You.mp3")
print("Get song title: " + song1.getTitle())
print("Get song artist: " + song1.getArtist())
print("Get song path: " + song1.getPath())
Exemplo n.º 26
0
 def load_songs(self):
     self.song_list.append(
         Song.Song(1, "Music/Waltz/Come Away With Me.mp3", 80, 17.25))
     self.song_list.append(
         Song.Song(2, "Music/Waltz/Dark Waltz.mp3", 87, 17))
Exemplo n.º 27
0
 def load_songs(self):
     self.song_list.append(Song.Song(1, "Music/EastCoast/Long Cool Woman.mp3", 139))
     self.song_list.append(Song.Song(2, "Music/EastCoast/Tush.mp3", 145))
Exemplo n.º 28
0
 def load_songs(self):
     self.song_list.append(Song.Song(1, "Music/ChaCha/Smooth.mp3", 120))
Exemplo n.º 29
0
   def getName(self, id):
       sql = "SELECT name FROM Album  WHERE id=?"
       return (DBQuery.getOne(sql, id)[0])

   def getSongs(self, id):
       sql = "SELECT songId FROM Album2Song  WHERE albumId=?"
       return (DBQuery.getList(sql, id))

   def find(self, pattern):
       sql = "SELECT id FROM Album  WHERE name LIKE {}".format("\'%"+pattern+"%\'")
       return (DBQuery.find(sql))

if __name__ == '__main__':
   myAlbum  = Album ()
   mySong   = Song.Song ()

   ### Get the album name
   print ("\n*** Album Name ***")
   print (myAlbum.getName(2))

   ### Find albums with pattern
   print ("\n*** Album Name ***")
   id = myAlbum.find ('Blue')
   print (myAlbum.getName(id[0][0]))
   
   ### Get the songs for the album
   print ("\n*** Song Names ***")
   songs = myAlbum.getSongs(2)
   for song in songs:
      print (mySong.getName(song[0]))
Exemplo n.º 30
0
 def load_songs(self):
     self.song_list.append(
         Song.Song(1, "Music/Rumba/She Will Be Loved.mp3", 102, 5.0))