def download_sfx(sound_id, counter): logger.info('Inside download_sfx...') client = freesound.FreesoundClient() client.set_token(config.FREESOUND_API_KEY) response = client.get_sound(sound_id) name = str(counter) + '.mp3' response.retrieve_preview(config.SFX_PATH, name=name)
def search_by_content(self, content=""): client = freesound.FreesoundClient() client.set_token(self.__api_key,"token") results = client.text_search(query=content,fields="id,name,previews") for sound in results: print(sound.name)
def download(self): logger.info('Downloading sfx...') client = freesound.FreesoundClient() client.set_token(config.FREESOUND_API_KEY) i = 0 while i < int(self.download_num): try: sound_id = random.randint(0, 96451) response = client.get_sound(sound_id) url = response.url args = ','.join( "{0}".format(arg) for arg in [str(sound_id), str(i)]) cmd = ['runp', 'Downloaders.py', 'download_sfx:' + args] p = subprocess.Popen(cmd) pid = utils.wait_timeout(p, config.DOWNLOAD_TIMEOUT) if pid is not None: logger.info('download_sfx successfully ran...') store(self.id, url, 'sfx') i += 1 else: logger.error('download_sfx function has timed out...') except Exception as e: logger.error('Exception occured while downloading sfx...') logger.error(e)
def download_by_id(self, id): client = freesound.FreesoundClient() client.set_token(self.__api_key,"token") sound = client.get_sound(id,fields="id,name,previews") sound.retrieve_preview(".",sound.name) print(sound.name + " - ID: "+str(sound.id))
def query_1(self, *args): """ This fetches sounds """ if len(args) != 2: print "invalid number of arguments, need query and number of items" return keyword = args[0] num_items = args[1] print "Fetching {0} sounds with query {1!s}".format(num_items, keyword) print "Saving in {0}".format(self.path) client = freesound.FreesoundClient() client.set_token("55217501132ecb9ada5da26888c7f0eac8ce1f45", "token") results = client.text_search(query=keyword, fields="id,name,previews") i = 0 for sound in results: if i < num_items: sound.retrieve_preview(self.path, sound.name) self.convert_wav(self.path + "/" + sound.name) print sound.name i += 1 else: break self._outlet(1, 1)
def search_by_mir(self, mir_state): client = freesound.FreesoundClient() client.set_token(self.__api_key,"token") desc_filter = "" desc_target = "" for desc,value in mir_state.iteritems(): if "TO" in str(value): print("Filter by: "+desc) desc_filter = desc+":["+value+"]" elif desc=="tags" or desc=="content": print("Tags/content not yet supported") else: print("Target: "+desc) desc_target += desc+":"+str(value) + " " print("Filter: "+desc_filter) print("Target: "+desc_target) # desc_filter = "lowlevel.pitch.var:[* TO 20]" # desc_target = "lowlevel.pitch_salience.mean:1.0 lowlevel.pitch.mean:440" results_pager = client.content_based_search( descriptors_filter=desc_filter, target=desc_target, fields="id,name,username" ) print("Num results:", results_pager.count) new_list = list() for sound in results_pager: print("\t-", sound.name, "by", sound.username) new_list.append(sound) print() return new_list
def download_by_content(self, content=""): client = freesound.FreesoundClient() client.set_token(self.__api_key,"token") results = client.text_search(query=content,fields="id,name,previews") for sound in results: sound.retrieve_preview(".",sound.name+".mp3") print(sound.name)
def download(): client = freesound.FreesoundClient() client.set_token("8B01Qr77J2Z911rWyOz852g5mZOo4fJxBiw23LMC", "token") results = client.text_search(query="dubstep", fields="id,name,previews") for sound in results: sound.retrieve_preview(".", sound.name + ".mp3") print(sound.name + "-downloaded")
def search_by_id(self, id=""): client = freesound.FreesoundClient() client.set_token(self.__api_key,"token") sound = client.get_sound(96541) # print("Getting sound:", sound.name) # print("Url:", sound.url) # print("Description:", sound.description) # print("Tags:", " ".join(sound.tags)) return sound
def __init__(self): api_key = os.getenv('FREESOUND_API_KEY', None) if api_key is None: print("You need to set your API key as an evironment variable",) print("named FREESOUND_API_KEY") sys.exit(-1) self.freesound_client = freesound.FreesoundClient() self.freesound_client.set_token(api_key)
def configure_freesound(): # Get user access token and configure client client = None try: client = freesound.FreesoundClient() client.set_token(FS_API_KEY) log('Freesound configured successfully!') except Exception as e: log('Could not connect to Freesound... %s' % str(e)) return client
def freesound_analysis(search_tokens, output, lim_page_count=1, key=None): lim_page_count = int(lim_page_count) try: client = freesound.FreesoundClient() client.set_token(key, "token") print(termcolor.colored("Authorisation successful ", "green")) except: print(termcolor.colored("Authorisation failed ", "red")) classes = list() for token in search_tokens: try: results = client.text_search(query=token, fields="id,name,previews") output_catalog = os.path.normpath(output) if not os.path.exists(output_catalog): os.makedirs(output_catalog) page_count = int(0) while True: for sound in results: try: classes.append(token) info = "Data has been getter: " + str(sound.name) print(termcolor.colored(info, "green")) except: info = "Data has not been getter: " + str(sound.name) print(termcolor.colored(info, "red")) page_count += 1 if (not results.next) or (lim_page_count == page_count): page_count = 0 break results = results.next_page() except: print(termcolor.colored(" Search is failed ", "red")) analysis.histogram(classes) pass
def soundApi(): print("soundApi") client = freesound.FreesoundClient() client.set_token("1TUvgpT0yJzOjjez0U5LrSLyWkwhWyJduZ3JK2YC", "token") results = client.text_search(query="scream", filter="type:wav duration:[0 TO 5]", fields="id,name") print(results) for result in results: # print(type(result)) # printes Sound class print(result) """
def search(term): client = freesound.FreesoundClient() client.set_token(TOKEN, "token") results = client.text_search(query=term, fields="id,duration,name,previews") # filter really short and long stuff out short_results = list( filter(lambda result: result.duration < 20 and result.duration > 1, results)) sound = random.choice(short_results) url = sound.previews.preview_lq_mp3 print(f'Using: {sound.name}') print(url) return url
def freesound_download(search_tokens, output, lim_page_count=1, key=None): lim_page_count = int(lim_page_count) try: client = freesound.FreesoundClient() client.set_token(key, "token") print(termcolor.colored("Authorisation successful ", "green")) except: print(termcolor.colored("Authorisation failed ", "red")) for token in search_tokens: try: results = client.text_search(query=token, fields="id,name,previews") output_catalog = os.path.normpath(output + "\\" + str(token)) if not os.path.exists(output_catalog): os.makedirs(output_catalog) page_count = int(0) while True: for sound in results: try: sound.retrieve_preview(output_catalog) info = "Saved file: " + str(output_catalog) + str( sound.name) print(termcolor.colored(info, "green")) except: info = str("Sound can`t be saved to " + str(output_catalog) + str(sound.name)) print(termcolor.colored(info, "red")) page_count += 1 if not results.next or lim_page_count == page_count: page_count = 0 break results = results.next_page() except: print(termcolor.colored(" Search is failed ", "red"))
def configure_freesound(): # Get user access token and configure client client = None try: resp = requests.post( 'https://freesound.org/apiv2/oauth2/access_token/', data={ 'client_id': FS_CLIENT_ID, 'grant_type': 'password', 'username': FS_UNAME, 'password': FS_PASSWORD, }) access_token = resp.json()['access_token'] client = freesound.FreesoundClient() client.set_token(access_token, auth_type='oauth') log('Freesound configured successfully!') except requests.exceptions.ConnectionError: log('Could not connect to Freesound...') return client
def exec_free_sound(keywords, keyword_download_path): api_key = '92wzjQFuwqNWWTC1QWXju3XFkkgEb2Catk3izPAz' freesound_client = freesound.FreesoundClient() freesound_client.set_token(api_key) download = mute_constants.FREESOUND_PATH + keyword_download_path for keyword in keywords: results_pager = freesound_client.text_search( query=keyword, # filter="tag:tenuto duration:[1.0 TO 15.0]", sort="rating_desc", fields="id,name,previews,username") os.makedirs(download, exist_ok=True) for sound in results_pager: print("\t-", sound.name, "by", sound.username) try: filename = str(sound.id) + '_' + sound.name.replace( u'/', '_') + ".wav" if not os.path.exists(download + filename): sound.retrieve_preview(download, filename) except Exception as err: print("[ Error keyword : " + keyword_download_path + " ]") print(err) print("Num results:", results_pager.count) for page_idx in range(results_pager.count): print("----- PAGE -----" + str(page_idx)) try: results_pager = results_pager.next_page() except Exception as err: print("[ Error keyword : " + keyword_download_path + " ]") print(err) break try: for sound in results_pager: print("\t-", sound.name, "by", sound.username) filename = str(sound.id) + '_' + sound.name.replace( u'/', '_') + ".wav" if not os.path.exists(download + filename): sound.retrieve_preview(download, filename) except Exception as err: print("[ Error keyword : " + keyword_download_path + " ]") print(err)
def query_by_voice(): c = freesound.FreesoundClient() c.set_token("<YOUR_API_KEY_HERE>", "token") d = record_audio() mfcc_frames = extract_mfcc(d) mfcc_mean = numpy.mean(mfcc_frames, 1) mfcc_var = numpy.var(mfcc_frames, 1) m = ",".join(["%.3f" % x for x in mfcc_mean]) v = ",".join(["%.3f" % x for x in mfcc_var]) results = c.content_based_search(target="lowlevel.mfcc.mean:"+m+" lowlevel.mfcc.var:"+v,\ fields="id,name,url,analysis", descriptors="lowlevel.mfcc.mean,lowlevel.mfcc.var", \ filter="duration:0 TO 3") for sound in results: print(sound.name) print(sound.url) print("--") return results
def get_pista_audio(id): """ Retorna el full path donde esta descargado el audio con ese id """ try: try: # try to find it locally desc = json.load(open(DATA_PATH + "/" + str(id) + ".json", 'r')) return flask.send_file(DATA_PATH + "/" + desc['filename']) except: print("Downloading from freesound.org first...") # Freesound setup auth_header = request.headers['Authorization'] api_key = auth_header.split(' ')[1] print("API KEY: " + api_key) freesound_client = freesound.FreesoundClient() freesound_client.set_token(api_key) try: sound = freesound_client.get_sound(id, fields="id,name,previews") sound.retrieve_preview(DATA_PATH, sound.name) print(sound.name + " - ID: " + str(sound.id)) sound_json = dict() sound_json['id'] = sound.id sound_json['name'] = sound.name sound_json['filename'] = sound.name with open(DATA_PATH + '/' + str(sound.id) + '.json', 'w') as outfile: json.dump(sound_json, outfile) print("New json created") except Exception, e: print(e) raise Exception("freesound api error") return flask.send_file(DATA_PATH + "/" + sound.name) except: abort(404) #not found
def main(): parser = argparse.ArgumentParser(description="Options") parser.add_argument("-s", "--search", help="Keyword for search", action="append", default=None, nargs="*") parser.add_argument("-o", "--out", help="Output catalog", default="../freesound") parser.add_argument("-l", "--lim_page", help="Limit of page", default=LIMIT_PAGE) args = parser.parse_args() search_tokens = list() keywords = args.search lim_page_count = args.lim_page output = os.path.normpath(args.out) for keyword in keywords: fusion_keyword = str() for k in keyword: fusion_keyword += k + ' ' if fusion_keyword[-1] == ' ': fusion_keyword = fusion_keyword[:-1] search_tokens.append(fusion_keyword) if not os.path.exists(output): os.makedirs(output) if search_tokens == None: raise Exception("Not found keywords") try: client = freesound.FreesoundClient() client.set_token(GEN_KEY_FREESOUND, "token") print(termcolor.colored("Authorisation successful ", "green")) except: print(termcolor.colored("Authorisation failed ", "red")) for token in search_tokens: try: results = client.text_search(query=token, fields="id,name,previews") output_catalog = os.path.normpath(output + "\\" + str(token)) if not os.path.exists(output_catalog): os.makedirs(output_catalog) page_count = int(0) while True: for sound in results: try: sound.retrieve_preview(output_catalog) info = "Saved file: " + str(output_catalog) + str( sound.name) print(termcolor.colored(info, "green")) except: info = str("Sound can`t be saved to " + str(output_catalog) + str(sound.name)) print(termcolor.colored(info, "red")) page_count += 1 if not results.next or lim_page_count == page_count: page_count = 0 break results = results.next_page() except: print(termcolor.colored(" Search is failed ", "red"))
def downloadFreesound(queryText='', tag=None, duration=None, API_Key='', outputDir='', topNResults=5, featureExt='.json', preview=True, emptyDir=False, folderName='', pack='', freeSoundId='', noDownload=False, normalizedDescriptors=True): """ This function downloads sounds and their descriptors from freesound using the queryText and the tag specified in the input. Additionally, you can also specify the duration range to filter sounds based on duration. Inputs: (Input parameters marked with a * are optional) queryText (string): query text for the sounds (eg. "violin", "trumpet", "cello", "bassoon" etc.) tag* (string): tag to be used for filtering the searched sounds. (eg. "multisample", "single-note" etc.) duration* (tuple): min and the max duration (seconds) of the sound to filter, eg. (0.2,15) API_Key (string): your api key, which you can obtain from : www.freesound.org/apiv2/apply/ outputDir (string): path to the directory where you want to store the sounds and their descriptors topNResults (integer): number of results(sounds) that you want to download featureExt (string): file extension for storing sound descriptors preview* (boolean): if true low quality sound is downloaded, if false high quality emptyDir* (boolean): if true the directory of name <queryText> will be deleted, if false downloaded sounds will bee added and the file list will be appended folderName* (string): the queryText was also used to give the download folder a name, setting this parameter has precedence and the query string can be empty pack* (string): filtering for freesound pack names freeSoundId* (string): download a sound using its freesound-id noDownload* (boolean): if true only the sound list will be printed output: This function downloads sounds and descriptors, and then stores them in outputDir. In outputDir it creates a directory of the same name as that of the queryText. In this directory outputDir/queryText it creates a directory for every sound with the name of the directory as the sound id. Additionally, this function also dumps a text file containing sound-ids and freesound links for all the downloaded sounds in the outputDir. NOTE: If the directory outputDir/queryText exists, it deletes the existing contents and stores only the sounds from the current query. """ if (queryText == "" and folderName == "" ) or API_Key == "" or outputDir == "" or not os.path.exists(outputDir): print "\n" print "Error: Wrong parameters" return -1 # Setting up the Freesound client and the authentication key fsClnt = fs.FreesoundClient() fsClnt.set_token(API_Key, "token") page_size = 30 filter = "" filter = appendQuery(filter, "tag", tag) filter = appendRangeQuery(filter, "duration", duration) filter = appendQuery(filter, "pack", pack) filter = appendQuery(filter, "id", freeSoundId) fields = 'id,name,username,url' if noDownload: fields += ',tags' else: fields += ',previews,analysis' search = { 'sort': 'score', 'fields': fields, 'page_size': page_size, 'normalized': 1 } if not noDownload: search['descriptors'] = ','.join(descriptors) if not queryText == "": search['query'] = queryText if not filter == "": search['filter'] = filter if not normalizedDescriptors: search['normalized'] = 0 qRes = fsClnt.text_search(**search) # Querying Freesound pageNo = 1 sndCnt = 0 indCnt = 0 totalSnds = min( qRes.count, 200) # System quits after trying to download after 200 times print "Found %s sounds:" % (str(qRes.count), ) if noDownload: if qRes.count == 0: return while True: if indCnt >= totalSnds: print "Not able to list required number of sounds..." return sound = qRes[indCnt - ((pageNo - 1) * page_size)] tags = ','.join(sound.tags) print "Found [id: %s], [name: %s], [url: %s], [tags: %s]" % (str( sound.id), sound.name, sound.url, tags) indCnt += 1 sndCnt += 1 if indCnt % page_size == 0: qRes = qRes.next_page() pageNo += 1 if sndCnt >= topNResults: break return if folderName == "": folderName = queryText outDir2 = os.path.join(outputDir, folderName) if os.path.exists(outDir2): if emptyDir: os.system("rm -r " + outDir2) os.mkdir(outDir2) else: os.mkdir(outDir2) # Creating directories to store output and downloading sounds and their descriptors downloadedSounds = [] while True: if indCnt >= totalSnds: print "Not able to download required number of sounds..." break sound = qRes[indCnt - ((pageNo - 1) * page_size)] print "Downloading mp3 and descriptors for sound with [id: %s], [name: %s], [url: %s]" % ( str(sound.id), sound.name, sound.url) outDir1 = os.path.join(outputDir, folderName, str(sound.id)) if os.path.exists(outDir1): os.system("rm -r " + outDir1) os.system("mkdir " + outDir1) soundPreview = sound.previews.preview_hq_mp3 if preview: soundPreview = sound.previews.preview_lq_mp3 mp3Path = os.path.join(outDir1, str(soundPreview.split("/")[-1])) ftrPath = mp3Path.replace('.mp3', featureExt) try: param = {'client': fsClnt, 'path': mp3Path, 'url': soundPreview} fs.FSRequest.retrieve(**param) features = {} # Initialize a dictionary to store descriptors for desc in descriptors: features[desc] = [] features[desc].append(eval("sound.analysis." + desc)) json.dump(features, open(ftrPath, 'w')) # store them in a json file sndCnt += 1 downloadedSounds.append([str(sound.id), sound.url]) except: if os.path.exists(outDir1): os.system("rm -r " + outDir1) indCnt += 1 if indCnt % page_size == 0: qRes = qRes.next_page() pageNo += 1 if sndCnt >= topNResults: break # Dump the list of files and Freesound links fid = open(os.path.join(outDir2, folderName + '_SoundList.txt'), 'ab+') fid.seek(0, 1) # seek end for elem in downloadedSounds: fid.write('\t'.join(elem) + '\n') fid.close()
import unicodecsv # For I/O import freesound # The Freesound.org API import time # To pause between calls to the website. import json def list_to_id_filter(sfx): sfxfilter = ' OR '.join(map(str,sfx)) return "id:(" + sfxfilter + ")" def chunks(l, n): """ Yield successive n-sized chunks from l. """ for i in xrange(0, len(l), n): yield l[i:i+n] c = freesound.FreesoundClient() # Initialize the client c.set_token(c.client_secret) # And set the security token def get_pager(my_filter, my_fields): return c.text_search( query='', page_size=150, fields=my_fields, filter=my_filter ) f = ['id', 'username', # ID info 'name', 'description', 'tags', 'avg_rating', 'num_ratings', # User-supplied descriptions 'type', 'duration', 'bitrate', 'bitdepth', 'channels', 'samplerate', # Sound information 'license', 'url','previews'] wanted_fields = ','.join(f)
def downloadSoundsFreesound(queryText="", tag=None, duration=None, API_Key="", outputDir="", topNResults=5, featureExt='.json'): """ This function downloads sounds and their descriptors from freesound using the queryText and the tag specified in the input. Additionally, you can also specify the duration range to filter sounds based on duration. Inputs: (Input parameters marked with a * are optional) queryText (string): query text for the sounds (eg. "violin", "trumpet", "cello", "bassoon" etc.) tag* (string): tag to be used for filtering the searched sounds. (eg. "multisample", "single-note" etc.) duration* (tuple): min and the max duration (seconds) of the sound to filter, eg. (0.2,15) API_Key (string): your api key, which you can obtain from : www.freesound.org/apiv2/apply/ outputDir (string): path to the directory where you want to store the sounds and their descriptors topNResults (integer): number of results(sounds) that you want to download featureExt (string): file extension for storing sound descriptors output: This function downloads sounds and descriptors, and then stores them in outputDir. In outputDir it creates a directory of the same name as that of the queryText. In this directory outputDir/queryText it creates a directory for every sound with the name of the directory as the sound id. Additionally, this function also dumps a text file containing sound-ids and freesound links for all the downloaded sounds in the outputDir. NOTE: If the directory outputDir/queryText exists, it deletes the existing contents and stores only the sounds from the current query. """ # Checking for the compulsory input parameters if queryText == "": print "\n" print "Provide a query text to search for sounds" return -1 if API_Key == "": print "\n" print "You need a valid freesound API key to be able to download sounds." print "Please apply for one here: www.freesound.org/apiv2/apply/" print "\n" return -1 if outputDir == "" or not os.path.exists(outputDir): print "\n" print "Please provide a valid output directory. This will be the root directory for storing sounds and descriptors" return -1 # Setting up the Freesound client and the authentication key fsClnt = fs.FreesoundClient() fsClnt.set_token(API_Key, "token") # Creating a duration filter string that the Freesound API understands if duration and type(duration) == tuple: flt_dur = " duration:[" + str(duration[0]) + " TO " + str( duration[1]) + "]" else: flt_dur = "" if tag and type(tag) == str: flt_tag = "tag:" + tag else: flt_tag = "" # Querying Freesound page_size = 30 if not flt_tag + flt_dur == "": qRes = fsClnt.text_search( query=queryText, filter=flt_tag + flt_dur, sort="score", fields="id,name,previews,username,url,analysis", descriptors=','.join(descriptors), page_size=page_size, normalized=1) else: qRes = fsClnt.text_search( query=queryText, sort="score", fields="id,name,previews,username,url,analysis", descriptors=','.join(descriptors), page_size=page_size, normalized=1) outDir2 = os.path.join(outputDir, queryText) if os.path.exists( outDir2 ): # If the directory exists, it deletes it and starts fresh os.system("rm -r " + outDir2) os.mkdir(outDir2) pageNo = 1 sndCnt = 0 indCnt = 0 totalSnds = min( qRes.count, 200) # System quits after trying to download after 200 times # Creating directories to store output and downloading sounds and their descriptors downloadedSounds = [] while (1): if indCnt >= totalSnds: print "Not able to download required number of sounds. Either there are not enough search results on freesound for your search query and filtering constraints or something is wrong with this script." break sound = qRes[indCnt - ((pageNo - 1) * page_size)] print "Downloading mp3 preview and descriptors for sound with id: %s" % str( sound.id) outDir1 = os.path.join(outputDir, queryText, str(sound.id)) if os.path.exists(outDir1): os.system("rm -r " + outDir1) os.system("mkdir " + outDir1) mp3Path = os.path.join( outDir1, str(sound.previews.preview_lq_mp3.split("/")[-1])) ftrPath = mp3Path.replace('.mp3', featureExt) try: fs.FSRequest.retrieve(sound.previews.preview_hq_mp3, fsClnt, mp3Path) # Initialize a dictionary to store descriptors features = {} # Obtaining all the descriptors for desc in descriptors: features[desc] = [] features[desc].append(eval("sound.analysis." + desc)) # Once we have all the descriptors, store them in a json file json.dump(features, open(ftrPath, 'w')) sndCnt += 1 downloadedSounds.append([str(sound.id), sound.url]) except: if os.path.exists(outDir1): os.system("rm -r " + outDir1) indCnt += 1 if indCnt % page_size == 0: qRes = qRes.next_page() pageNo += 1 if sndCnt >= topNResults: break # Dump the list of files and Freesound links fid = open(os.path.join(outDir2, queryText + '_SoundList.txt'), 'w') for elem in downloadedSounds: fid.write('\t'.join(elem) + '\n') fid.close()
import freesound import subprocess c = freesound.FreesoundClient() c.set_token("36e286ba563287f86eed608c13cacd520ced010e","token") text_file = open('../data/text/sonar_knights.txt', 'r') words = text_file.read().split() sounds = {} i = 0 for word in words: i = i+1 if word not in sounds.keys() and '.' in word: word = word.replace('.', '') print "Searching for " + word + ":" print "----------------------------" results_pager = c.text_search(query=word, filter="duration:[0.5 TO 3]" , sort="downloads_desc", fields="id,name,previews") if len(results_pager.results) > 0: sounds[word] = results_pager[0].retrieve_preview('.', word+'.mp3') convertedfile = word+'.mp3' outputfilename = '../data/audio/' + str(i)+'.mp3' cmd = 'lame --resample 44.1 ' + convertedfile + ' ' + outputfilename subprocess.call(cmd, shell=True)
def downloadSoundsFreesound(queryText="", API_Key="", outputDir="", topNResults=5, tag=None, duration=None, featureExt='.json'): """ This function downloads sounds and their descriptors from freesound based on the queryText and the tag specified in the input. Additionally to filter the sounds based on the duration you can also specify the duration range. Inputs: queryText (string): query text for the sounds (eg. "violin", "trumpet", "bass", "Carnatic" etc.) tag* (string): tag to be used while searching for sounds. (eg. "multisample" etc.) duration* (tuple): min and the max duration (seconds) of the sound to filter (eg (1,15)) API_Key (string): your api key, which you can obtain from : www.freesound.org/apiv2/apply/ outputDir (string): path to the directory where you want to store the sounds and their descriptors topNResults (integer): number of results/sounds that you want to download output: This function downloads sounds and descriptors and stores them in appropriate folders within outputDir. The name of the directory for each sound is the freesound id of that sound. NOTE: input parameters with * are optional. """ #checking if the compulsory input parameters are provided if queryText == "": print "\n" print "Provide a query text to search for sounds" return -1 if API_Key == "": print "\n" print "You need a valid freesound API key to be able to download sounds." print "Please apply for one here: www.freesound.org/apiv2/apply/" print "\n" return -1 if outputDir == "" or not os.path.exists(outputDir): print "\n" print "Please provide a valid output directory" return -1 #checking authentication stuff fsClnt = fs.FreesoundClient() fsClnt.set_token(API_Key, "token") #creating a filter string which freesound API understands if duration and type(duration) == tuple: flt_dur = " duration:[" + str(duration[0]) + " TO " + str( duration[1]) + "]" else: flt_dur = "" if tag and type(tag) == str: flt_tag = "tag:" + tag else: flt_tag = "" #querying freesund page_size = 20 if not flt_tag + flt_dur == "": qRes = fsClnt.text_search( query=queryText, filter=flt_tag + flt_dur, sort="rating_desc", fields="id,name,previews,username,url,analysis", descriptors=','.join(descriptors), page_size=page_size, normalized=1) else: qRes = fsClnt.text_search( query=queryText, sort="rating_desc", fields="id,name,previews,username,url,analysis", descriptors=','.join(descriptors), page_size=page_size, normalized=1) outDir2 = os.path.join(outputDir, queryText) if os.path.exists(outDir2): os.system("rm -r " + outDir2) os.mkdir(outDir2) pageNo = 1 sndCnt = 0 indCnt = 0 totalSnds = qRes.count #creating directories to store output and downloading sounds and their descriptors while (1): sound = qRes[indCnt - ((pageNo - 1) * page_size)] outDir1 = os.path.join(outputDir, queryText, str(sound.id)) if os.path.exists(outDir1): os.system("rm -r " + outDir1) os.system("mkdir " + outDir1) mp3Path = os.path.join( outDir1, str(sound.previews.preview_lq_mp3.split("/")[-1])) ftrPath = mp3Path.replace('.mp3', featureExt) try: fs.FSRequest.retrieve(sound.previews.preview_lq_mp3, fsClnt, mp3Path) #initialize dictionary to store features/descriptors features = {} #obtaining all the features/descriptors for desc in descriptors: features[desc] = [] features[desc].append(eval("sound.analysis." + desc)) #once we have all the descriptors, lets store them in a json file json.dump(features, open(ftrPath, 'w')) sndCnt += 1 except: if os.path.exists(outDir1): os.system("rm -r " + outDir1) indCnt += 1 if indCnt % page_size == 0: qRes = qRes.next_page() pageNo += 1 if sndCnt >= topNResults or indCnt >= totalSnds: break
raise FileNotFoundError("Please authorize the application first using " "`python freesound_download.py --authorize`") if args.data_dir == '': raise ValueError( "Data dir must be passed as an argument using `--data_dir`") data_dir = args.data_dir page_size = args.page_size max_num_samples = args.max_samples min_filesize_in_mb = args.min_filesize max_filesize_in_mb = args.max_filesize # Initialize and authenticate client token = unpickle_object('_token') freesound_client = freesound.FreesoundClient() client = prepare_client(freesound_client, token) category = args.category if category == '': raise ValueError( "Cannot pass empty string as it will select all of FreeSound data !" ) print(f"Downloading category : {category}") get_songs_by_category( client, category, data_dir=data_dir, max_num_samples=max_num_samples,
def downloadFreesound( queryText = '', tag=None, duration = None, API_Key = '', outputDir = '', topNResults = 5, featureExt = '.json', preview=True, emptyDir=False, omitQueryText=False, pack='', freeSoundId=''): if queryText == "" or API_Key == "" or outputDir == "" or not os.path.exists(outputDir): print "\n" print "Error: Wrong parameters" return -1 # Setting up the Freesound client and the authentication key fsClnt = fs.FreesoundClient() fsClnt.set_token(API_Key,"token") page_size = 30 filter = "" if tag and type(tag) == str: flt_tag = "tag:\""+tag+"\"" filter += flt_tag if duration and type(duration) == tuple: flt_dur = "duration:[" + str(duration[0])+ " TO " +str(duration[1]) + "]" if not filter == "": filter += ' ' filter += flt_dur if pack and type(pack) == str: flt_pack = "pack:\""+pack+"\"" if not filter == "": filter += ' ' filter += flt_pack if freeSoundId and type(freeSoundId) == str: flt_freeSoundId = "id:\""+freeSoundId+"\"" if not filter == "": filter += ' ' filter += flt_freeSoundId search = {'sort':'score', 'fields':'id,name,previews,username,url,analysis', 'descriptors':','.join(descriptors), 'page_size':page_size, 'normalized':1} if not omitQueryText: search['query'] = queryText if not filter == "": search['filter'] = filter qRes = fsClnt.text_search(**search) # Querying Freesound outDir2 = os.path.join(outputDir, queryText) if os.path.exists(outDir2): if emptyDir: os.system("rm -r " + outDir2) os.mkdir(outDir2) else: os.mkdir(outDir2) pageNo = 1 sndCnt = 0 indCnt = 0 totalSnds = min(qRes.count,200) # System quits after trying to download after 200 times # Creating directories to store output and downloading sounds and their descriptors downloadedSounds = [] while(1): if indCnt >= totalSnds: print "Not able to download required number of sounds..." break sound = qRes[indCnt - ((pageNo-1)*page_size)] print "Downloading mp3 and descriptors for sound with id: %s"%str(sound.id) outDir1 = os.path.join(outputDir, queryText, str(sound.id)) if os.path.exists(outDir1): os.system("rm -r " + outDir1) os.system("mkdir " + outDir1) mp3Path = os.path.join(outDir1, str(sound.previews.preview_lq_mp3.split("/")[-1])) ftrPath = mp3Path.replace('.mp3', featureExt) try: param = {'client':fsClnt, 'path':mp3Path, 'url':sound.previews.preview_hq_mp3} if preview: param['url'] = sound.previews.preview_lq_mp3 fs.FSRequest.retrieve(**param) features = {} # Initialize a dictionary to store descriptors for desc in descriptors: features[desc]=[] features[desc].append(eval("sound.analysis."+desc)) json.dump(features, open(ftrPath,'w')) # store them in a json file sndCnt+=1 downloadedSounds.append([str(sound.id), sound.url]) except: if os.path.exists(outDir1): os.system("rm -r " + outDir1) indCnt +=1 if indCnt%page_size==0: qRes = qRes.next_page() pageNo+=1 if sndCnt>=topNResults: break # Dump the list of files and Freesound links fid = open(os.path.join(outDir2, queryText+'_SoundList.txt'), 'ab+') fid.seek(0, 1) # seek end for elem in downloadedSounds: fid.write('\t'.join(elem)+'\n') fid.close()
def Initialize(): self.freesound = freesound.FreesoundClient() self.freesound.set_token("<your_api_key>", "token")
def __init__(self, auth): self.cli = freesound.FreesoundClient() self.__results_pager = None self.cli.set_token(auth.access_token, auth.token_type)
def post_search(): """ Makes the search and returns the ID """ try: request_json = request.get_json() bpm = request_json.get('BPM') duration = request_json.get('duration') spectral_centroid = request_json.get('spectral_centroid') inharmonicity = request_json.get('inharmonicity') # print(bpm, duration, spectral_centroid, inharmonicity) response_content = None # Freesound setup auth_header = request.headers['Authorization'] api_key = auth_header.split(' ')[1] # print("API KEY: "+api_key) freesound_client = freesound.FreesoundClient() freesound_client.set_token(api_key) # bpm = 120 # inharmonicity = 10 duration = float(duration) print("Max duration: %f" % duration) # Content based search example print("Content based search:") print("---------------------") results_pager = freesound_client.content_based_search( # page_size=10, descriptors_filter="sfx.duration:[* TO %f]" % (duration), #descriptors_filter="sfx.duration:[* TO %f] sfx.inharmonicity:[* TO %f]"%(duration,inharmonicity), # target='rhythm.bpm: %f lowlevel.spectral_centroid: %f'%(bpm,spectral_centroid) ) # results_pager = freesound_client.content_based_search( # descriptors_filter="lowlevel.pitch.var:[* TO 20]", # target='lowlevel.pitch_salience.mean:1.0 lowlevel.pitch.mean:440' # ) print("Num results:", results_pager.count) for sound in results_pager: print("\t-", sound.name, "by", sound.username) print() #Note: min between results and page size to avoid get newer pages #selected = min( random.randint(0,results_pager.count-1), 10-1) selected = random.randint(0, 10 - 1) #FIXME print("Selected: %i" % selected) sound = results_pager[selected] response_content = dict() try: response_content['id'] = sound.id response_content['name'] = sound.name try: response_content['description'] = sound.description except: max_tags = 5 i = 0 response_content['description'] = "" for tag in sound.tags: if i >= max_tags: break response_content['description'] += str(tag) + ', ' i += 1 response_content['description'] = response_content[ 'description'][:-2] response_content['license'] = sound.license except: pass print(response_content) return jsonify(response_content) except: abort(404) #not found