def detectMusic(): mp3_file_content_to_recognize = open( r'C:\Users\sub\Desktop\musica\files\audio\file.mp3', 'rb').read() shazam = Shazam(mp3_file_content_to_recognize) try: recognize = shazam.recognizeSong() result = next(recognize) title = result[1]['track']['title'] artist = result[1]['track']['subtitle'] replytomessage = "This song is: " + title + " by " + artist + "." for mention in mentions: api.update_status(status=replytomessage, in_reply_to_status_id=mention.id, auto_populate_reply_metadata=True) return except: for mention in mentions: api.update_status(status="The song could not be recognized.", in_reply_to_status_id=mention.id, auto_populate_reply_metadata=True) traceback.print_exc() return
async def shazamcmd(event): "To reverse search song." reply = await event.get_reply_message() mediatype = media_type(reply) if not reply or not mediatype or mediatype not in ["Voice", "Audio"]: return await edit_delete( event, "__Reply to Voice clip or Audio clip to reverse search that song.__" ) catevent = await edit_or_reply(event, "__Downloading the audio clip...__") try: for attr in getattr(reply.document, "attributes", []): if isinstance(attr, types.DocumentAttributeFilename): name = attr.file_name dl = io.FileIO(name, "a") await event.client.fast_download_file( location=reply.document, out=dl, ) dl.close() mp3_fileto_recognize = open(name, "rb").read() shazam = Shazam(mp3_fileto_recognize) recognize_generator = shazam.recognizeSong() track = next(recognize_generator)[1]["track"] except Exception as e: LOGS.error(e) return await edit_delete( catevent, f"**Error while reverse searching song:**\n__{str(e)}__") image = track["images"]["background"] song = track["share"]["subject"] await event.client.send_file(event.chat_id, image, caption=f"**Song:** `{song}`", reply_to=reply) await catevent.delete()
def getDetails(fileloc, all=False): content = open(fileloc, 'rb').read() shazam = Shazam(content) gen = shazam.recognizeSong() res = next(gen) returnees = [] if all: return res try: Details_of_song.insert(1, res[1]["track"]["share"]["subject"]) except: Details_of_song.insert(1, "Title not found!") try: Details_of_song.insert( 2, res[1]["track"]["sections"][1]['footer'].split(maxsplit=6)) except: Details_of_song.insert(2, "Details not found!") try: Details_of_song.insert(3, "Lyrics: ") i = 4 for lines in res[1]["track"]["sections"][1]["text"]: Details_of_song.insert(i, lines) i += 1 except: Details_of_song.insert(3, "Lyrics not found!")
def get_song_info(song): global issues title = None song_artist = None album = None song_genre = None album_artist = None image_url = None print("Getting song info") mp3_file_content_to_recognize = open(song, 'rb').read() shazam = Shazam(mp3_file_content_to_recognize) recognize_generator = shazam.recognizeSong() d = next(recognize_generator) for var in range(len(d)): if isinstance(d[var], dict): matches = d[var].get('matches') if not matches: break tdict = d[var].get('track') title = tdict.get("title") if title is None: issues += "No title, " song_artist = tdict.get("subtitle") if song_artist is None: issues += "No song artist, " for item in tdict.get("sections"): if isinstance(item, dict): metadata = item.get("metadata") if metadata is not None: for a in metadata: album = a.get("text") break # print('Sections: ', tdict.get("sections")) genres = tdict.get("genres") if genres is None: song_genre = "" issues += "No genres, " else: song_genre = genres.get("primary") urlparams = tdict.get("urlparams") if isinstance(urlparams, dict): album_artist = list(urlparams.values())[-1] album_artist = album_artist.replace("+", " ") idict = tdict.get("images") if isinstance(idict, dict): image_url = idict.get("coverart") return title, song_artist, album, song_genre, album_artist, image_url
async def _shazam(self, data: bytes): shazam = Shazam(data) loop = asyncio.get_event_loop() for _, content in shazam.recognizeSong(): print(content) content = content break return content
def name_song(path): try: mp3_file_content_to_recognize = open(path, 'rb').read() shazam = Shazam(mp3_file_content_to_recognize) recognize_generator = shazam.recognizeSong() for i, response in enumerate(next(recognize_generator)): if i > 0: return (response['track']['title']) except: return ("A música não foi reconhecida")
def run_jarvis(): command = take_command() print(command) if 'play' in command: song = command.replace('play', '') talk('playing ' + song) pywhatkit.playonyt(song) elif 'time' in command: time = datetime.datetime.now().strftime('%I:%M %p') talk('Current time is ' + time) elif 'who is ' in command: person = command.replace('who is', '') info = wikipedia.summary(person, 1) print(info) talk(info) elif 'date' in command: date = datetime.datetime.now() day=str(date.day) month=str(date.month) year=str(date.year) talk('Todays date is ' + day ) talk(month) talk(year) elif 'are you single' in command: talk('I am in a relationship with wifi') elif 'joke' in command: talk(pyjokes.get_joke()) elif 'hello' in command: talk('Hello sir') elif 'how are you today' in command: talk('I am good sir') elif 'which song is this' in command: mp3_file_content_to_recognize = open('a.mp3', 'rb').read() shazam = Shazam(mp3_file_content_to_recognize) recognize_generator = shazam.recognizeSong() while True: talk(next(recognize_generator)) else: talk('Please say the command again.')
def shazamAsync(data, round = 0): print('''%%%%%%%%%%% SHAZAMMING %%%%%%%%%%%''') print('''%%%%%%%%%%% SHAZAMMING %%%%%%%%%%%''') print('''%%%%%%%%%%% SHAZAMMING %%%%%%%%%%%''') t = time.time() try: mp3path, outDict, checkFull = data if checkFull: mp3_file_content_to_recognize = open(mp3path, 'rb').read() else: audio = AudioSegment.from_mp3(mp3path) mp3_file_content_to_recognize = audio.export(format="mp3").read() start = 0 seconds = 1.2 length = len(audio) if length > 0: if length > seconds: seconds = seconds else: seconds = length/1000 mp3_file_content_to_recognize = mp3_file_content_to_recognize[start*60*1000:int((start+seconds)*60*1000)] # shazam = Shazam(mp3_file_content_to_recognize) outDict["out"] = next(Shazam(mp3_file_content_to_recognize).recognizeSong()) # recognize_generator = shazam.recognizeSong() # outDict["out"] = next(recognize_generator) if outDict is not None: firstRes = None try: print(firstRes) firstRes = outDict["out"][1]["track"] except: print("EEEEE SHAZAM COULD NOT FIND SONG") traceback.print_exc() if firstRes is not None and "title" in firstRes and "subtitle" in firstRes: outDict["title"] = firstRes["title"] outDict["artist"] = firstRes["subtitle"] print(outDict["title"] + " - " + outDict["artist"]) print('''%%%%%%%%%%% DONE! %%%%%%%%%%%''', "time",time.time()-t) # while True: # print(next(recognize_generator)) # current offset & shazam response to recognize requests1 except: traceback.print_exc()
def shazam_recognize_from_link(_link): # Function that returns recognized song from given link to an mp3 file on web. if not __shazam_enabled: # If shazam is not enabled. # Raising error. raise ImportError # Debug message. if __loguru_enabled: logger.debug("Started Shazam recognition!") # Getting filename. _filename = os.getcwd() + "\\voicemessage.mp3" # Downloading file. _downloadfile = requests.get(_link) open(_filename, 'wb').write(_downloadfile.content) # Debug message. if __loguru_enabled: logger.debug("Downloaded voice message!") # Getting shazam API. _API_SHAZAM = Shazam(open(_filename, "rb").read()) _API_SHAZAM_GENERATOR = _API_SHAZAM.recognizeSong() # Default response _response = None for _song in _API_SHAZAM_GENERATOR: # For every song in the generator. # Getting song (removing offset) _song = _song[1] if "track" in _song: # If there is any track. # Getting track. _song = _song["track"] if "title" and "subtitle" in _song: # If there title and subtitle. # Getting response, _response = STRINGS["shazam-message-founded"].format( _song['title'], _song['subtitle']) if "images" in _song and "coverart" in _song["images"]: # Getting image if exists. _response += f"\n{_song['images']['coverart']}" # Breaking. break # Debug message. if __loguru_enabled: logger.debug(f"End recognition of the song!") # Response return _response