def search_track(spotify): """ This demo function will allow the user to search a song title and pick the song from a list in order to fetch the audio features/analysis of it :param spotify: An basic-authenticated spotipy client """ keep_searching = True selected_track = None # Initialize Spotipy spotify = authenticate_client() # We want to make sure the search is correct while keep_searching: search_term = input('\nWhat song would you like to search: ') # Search spotify results = spotify.search(search_term) tracks = results.get('tracks', {}).get('items', []) if len(tracks) == 0: print_header('No results found for "{}"'.format(search_term)) else: # Print the tracks print_header('Search results for "{}"'.format(search_term)) for i, track in enumerate(tracks): print(' {}) {}'.format(i + 1, track_string(track))) # Prompt the user for a track number, "s", or "c" track_choice = input( '\nChoose a track #, "s" to search again, or "c" to cancel: ') try: # Convert the input into an int and set the selected track track_index = int(track_choice) - 1 selected_track = tracks[track_index] keep_searching = False except (ValueError, IndexError): # We didn't get a number. If the user didn't say 'retry', then exit. if track_choice != 's': # Either invalid input or cancel if track_choice != 'c': print('Error: Invalid input.') keep_searching = False # Quit if we don't have a selected track if selected_track is None: return # Request the features for this track from the spotify API # get_audio_features(spotify, [selected_track]) return [selected_track]
def get_audio_analysis(spotify, tracks, pretty_print=False): """ Given a list of tracks, get and print the audio analysis for those tracks! :param spotify: An authenticated Spotipy instance :param tracks: A list of track dictionaries """ if not tracks: print('No tracks provided.') return # Build a map of id->track so we can get the full track info later track_map = {track.get('id'): track for track in tracks} # Request the audio analysis for each track -- one at a time since these # can be really big tracks_analysis = {} #i = 0 print_header('Getting Audio Audio Analysis...') for track_id in track_map.keys(): analysis = spotify.audio_analysis(track_id) tracks_analysis[track_id] = analysis # Print out the track info and audio features if pretty_print: track = track_map.get(track_id) #not necessary, just sets up txt file to print song data to, this was for testing purposes new_path = '/Users/chrissamra/Desktop/spotify-api-starter-master/src/song.txt' new_song = open(new_path, 'w+') new_song.write('\n' '{}'.format(track_string(track) + '\n')) new_song.write('{ "notes" : [\n') print('{}'.format(track_string(track))) #returns track name time.sleep(5) #waits 5 seconds before starting i = 0 for seg in analysis[ "segments"]: #iterates through every segment of the song pitches = [] for cur_pitch in seg.get( "pitches"): #checks every pitch in current segment #if pitch confidence is over 75% add to list of pitches if cur_pitch >= 0.75: pitches.append(cur_pitch) #if multiple pitches are over 75% confidence if len(pitches) > 1: cleanDict = { "note_time": seg.get("start"), "note_duration": seg.get("duration"), "note_value": pitches } #gets relevant segment info synthbot(cleanDict) #sends data to synthbot function # if the first pitch and consecutive pitches in the list are normalized to 1 (no noize) elif seg.get("pitches").index(1.0) == 0 and seg.get( "pitches")[1] == 1: pitch = -1 cleanDict = { "note_time": seg.get("start"), "note_duration": seg.get("duration"), "note_value": pitch } #gets relevant segment info synthbot(cleanDict) #sends data to synthbot function #if only one pitch has over 75% confidence else: pitch = seg.get("pitches").index(1.0) cleanDict = { "note_time": seg.get("start"), "note_duration": seg.get("duration"), "note_value": pitch } #gets relevant segment info synthbot(cleanDict) #sends data to synthbot function #not necessary, just outputs song data to terminal for testing purposes new_song.write(json.dumps(cleanDict, indent=2) + ',') print(json.dumps(cleanDict, indent=2)) i += 1 #not necessary, just outputs song data to txt file for testing purposes new_song = open(new_path, "r") d = new_song.read() m = d.split("\n") s = "\n".join(m[:-1]) new_song.close() new_song = open(new_path, "w+") for n in range(len(s)): new_song.write(s[n]) new_song.write('}]}') print("total segments:" + str(i) + "") new_song.close() return tracks_analysis