Skip to content

Instantly share code, notes, and snippets.

@RobertHue
Last active January 6, 2022 19:17
Show Gist options
  • Save RobertHue/4b56704bdeb98eec74d4523963df97d8 to your computer and use it in GitHub Desktop.
Save RobertHue/4b56704bdeb98eec74d4523963df97d8 to your computer and use it in GitHub Desktop.
Renames detected sound files to the corresponding songs in it.
'''
Renames detected sound files to the corresponding songs in it.
note: all sound files in current directory and all subdirectories are renamed
note: does not rename when the song could not be detected
note: new sound file name will be consisting of the following
author - title
Pre-requisites:
- Install Python3
- Install pip3
- pip3 install ShazamAPI
- sudo apt install ffmpeg
'''
import json # for pretty print
import os
from ShazamAPI import Shazam
for root, dirs, files in os.walk('.', topdown=True):
for name in files:
if name.endswith(('.ogg', '.wma', '.mp3', 'm4a')):
music_file = os.path.join(root, name)
print(music_file)
mp3_file_content_to_recognize = open(music_file, 'rb').read()
shazam = Shazam(mp3_file_content_to_recognize)
recognize_generator = shazam.recognizeSong()
obj = next(recognize_generator) # current offset & shazam response to recognize requests
for i in obj:
if type(i) is dict:
if (len(i.get('matches')) > 0): # only get info when there are matches found
print("i: ", json.dumps(i, indent=4))
track = i.get('track')
title = track.get('title')
subtitle = track.get('subtitle')
f_name, f_ext = os.path.splitext(music_file)
new_name = subtitle + ' - ' + title + f_ext
os.rename(music_file, os.path.join(root, new_name))
print('renamed "' + music_file + '" to "' + os.path.join(root, new_name) + '".')
print('-----------------------------------------------------\n\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment