Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_add_tags_already_there(self):
mp3 = MP3(os.path.join(DATA_DIR, "silence-44-s.mp3"))
self.failUnless(mp3.tags)
self.failUnlessRaises(Exception, mp3.add_tags)
def setUp(self):
self.filename = get_temp_copy(
os.path.join(DATA_DIR, "silence-44-s.mp3"))
self.mp3 = MP3(self.filename)
self.mp3_2 = MP3(self.silence_nov2)
self.mp3_3 = MP3(self.silence_mpeg2)
self.mp3_4 = MP3(self.silence_mpeg25)
self.mp3_lame = MP3(self.lame)
self.mp3_lame_peak = MP3(self.lame_peak)
unless proxied_track is set.
"""
if filename:
self._track = gpod.itdb_track_new()
self['userdata'] = {'transferred': 0,
'hostname': socket.gethostname(),
'charset':defaultencoding}
self['userdata']['pc_mtime'] = os.stat(filename).st_mtime
self._set_userdata_utf8('filename',filename)
possible_image = os.path.join(os.path.split(filename)[0],'folder.jpg')
if os.path.exists(possible_image):
self.set_thumbnail(possible_image)
try:
audiofile = MP3(self._userdata_into_default_locale('filename'))
except Exception, e:
raise TrackException(str(e))
for tag, attrib in (('TPE1','artist'),
('TIT2','title'),
('TBPM','BPM'),
('TCON','genre'),
('TALB','album'),
('TPOS',('cd_nr','cds')),
('TRCK',('track_nr','tracks'))):
try:
value = audiofile[tag]
if isinstance(value,mutagen.id3.NumericPartTextFrame):
parts = map(int,value.text[0].split("/"))
if len(parts) == 2:
self[attrib[0]], self[attrib[1]] = parts
elif len(parts) == 1:
def embed_artwork(track_filename, artwork_filename):
audio = MP3(track_filename, ID3=ID3)
# add ID3 tag if it doesn't exist
try:
audio.add_tags()
except error:
pass
audio.tags.add(
APIC(
encoding=3, # 3 is for utf-8
mime='image/jpg', # image/jpeg or image/png
type=3, # 3 is for the cover image
desc=u'Cover',
data=open(artwork_filename).read()
)
)
audio.save()
audio = EasyMP3(file)
audio.tags = None
audio["artist"] = getTrack().user["username"] #depending on who uploaded the song, this may not always be the actual artist of the song
audio["title"] = getTrack().title
audio["genre"] = getTrack().genre
audio.save()
artworkURL = getTrack().artwork_url #gets url of artwork for song provided...
if "large" in artworkURL: #...but we need to replace "large" with "t500x500"...
artworkURL = artworkURL.replace("large", "t500x500") #...to get a decent sized photo that isn't pixelated for the cover art of the mp3
image_data = requests.get(artworkURL).content
mime = 'image/jpeg'
if '.jpg' in artworkURL:
mime = 'image/jpeg'
if '.png' in artworkURL:
mime = 'image/png'
audio = MP3(file, ID3=OldID3)
audio.tags.add(
APIC(
encoding=3, #3 is for utf-8
mime=mime,
type=3, #3 is for the cover image
desc='Cover',
data=image_data
)
)
audio.save()
except Exception as e:
print(e)
except: pass
try: info.artist = audio["artist"][0]
except: pass
try: info.tracknumber = "{:0>2}".format(audio["tracknumber"][0])
except: pass
try: info.genre = audio["genre"][0]
except: pass
try: info.date = audio["date"][0]
except: pass
except Exception as e:
pass
# try to read MP3 information (bitrate, length, samplerate)
try:
with open(filename, 'rb') as mpfile:
mpinfo = MP3(mpfile).info
info.bitrate = str(mpinfo.bitrate / 1000) + " Kbps"
info.samplerate = str(mpinfo.sample_rate) + " Hz"
# [SabreWolfy] added consistent formatting of times in format hh:mm:ss
# [SabreWolfy[ to allow for correct column sorting by length
info.length = "%02i:%02i:%02i" % ((int(mpinfo.length/3600)), (int(mpinfo.length/60%60)), (int(mpinfo.length%60)))
except Exception:
pass
# image handling
elif file.is_mime_type('image/jpeg') or file.is_mime_type('image/png') or file.is_mime_type('image/gif') or file.is_mime_type('image/bmp'):
# EXIF handling routines
try:
metadata = GExiv2.Metadata(path=filename)
try:
info.exif_datetime_original = str(metadata.get_date_time())
def load_tag_from_file(self, filename):
"""
Reads ID3 tags and sets object-level variables.
"""
# log.debug("playlist", u"reading tag info from {}".format(filename))
f = MP3(filename, translate=False)
self.filename = filename
if not f.tags:
raise PassableScanError("Song filename \"%s\" has no tags." % filename)
w = f.tags.getall('TIT2')
if len(w) > 0 and len(unicode(w[0])) > 0:
self.data['title'] = unicode(w[0]).strip()
else:
raise PassableScanError("Song filename \"%s\" has no title tag." % filename)
w = f.tags.getall('TPE1')
if len(w) > 0 and len(unicode(w[0])) > 0:
self.artist_tag = unicode(w[0])
else:
raise PassableScanError("Song filename \"%s\" has no artist tag." % filename)
w = f.tags.getall('TALB')
def print_info(release, files):
print
print "%s - %s - %s - %s tracks" % (
release.artist.name, release.title,
release.earliestReleaseDate,
release.tracks_total)
print " " + "Musicbrainz track".center(35) + " | " + "Filename".center(35)
files_and_tracks = zip(files, release.tracks)
for i, (file, track) in enumerate(files_and_tracks):
basename = os.path.basename(file)
mp3 = MP3(file)
file_duration = format_seconds(mp3.info.length)
track_duration = format_seconds((track.duration or 0)/1000)
print "%2s. %-30s %4s | %-30s %4s" % (i + 1, track.title, track_duration, basename, file_duration)
set_m4a_tags(audio)
audio = mp4.MP4(audio_file)
elif args.output_type == "alac.m4a":
if sys.version_info >= (3, 0):
from mutagen import mp4
audio = mp4.MP4(audio_file)
set_mp4_tags(audio)
else:
from mutagen import m4a, mp4
audio = m4a.M4A(audio_file)
set_m4a_tags(audio)
audio = mp4.MP4(audio_file)
elif args.output_type == "mp3":
audio = mp3.MP3(audio_file, ID3=id3.ID3)
set_id3_tags(audio)
def bit_rate_str(bit_rate):
brs = "%d kb/s" % bit_rate
if not args.cbr:
brs = "~" + brs
return brs
def mode_str(mode):
modes = ["Stereo", "Joint Stereo", "Dual Channel", "Mono"]
if mode < len(modes):
return modes[mode]
else:
return ""
def channel_str(num):
def _get_mp3_tags(track, path):
"""
Tries to load embedded tags from given file.
:return: TrackData object
"""
track_data = TrackData(path)
log.debug("Importing mp3 " + track.path)
try:
track.mutagen = ID3(path)
except Exception as e:
log.warning("Track " + track.path +
" has no mp3 tags. Now guessing from file and folder name...")
return track_data
mp3 = TrackContainer(MP3(track.path), path)
track_data.cover = __get_mp3_tag(track, "APIC")
track_data.length = __get_common_track_length(mp3)
track_data.disk = __get_mp3_tag(track, "TPOS")
# for mp3 we are using the easyid3 functionality
# because its syntax compatible to the rest
track.mutagen = EasyID3(path)
track_data.author = __get_mp3_tag(mp3, "TCOM")
track_data.reader = __get_mp3_tag(mp3, "TPE1")
track_data.book_name = __get_common_tag(track, "album")
track_data.name = __get_common_tag(track, "title")
# other fields for the author and reader
if track_data.author is None or track_data.author == "":
track_data.author = __get_mp3_tag(mp3, "TPE1")
track_data.reader = __get_mp3_tag(mp3, "TPE2")