本文整理汇总了Python中mutagen.File类的典型用法代码示例。如果您正苦于以下问题:Python File类的具体用法?Python File怎么用?Python File使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了File类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save
def save(pf):
metadata = Metadata()
metadata.copy(pf.metadata)
mf = MFile(pf.filename)
if mf is not None:
mf.delete()
return pf._save_and_rename(pf.filename, metadata)
示例2: ensure_id3_tag_present
def ensure_id3_tag_present(filepath):
try:
meta = EasyID3(filepath)
except ID3NoHeaderError:
meta = File(filepath, easy=True)
meta.add_tags()
meta.save()
示例3: fetch_metadata
def fetch_metadata(top):
for dirpath, dirnames, filenames in os.walk(top):
for filename in filenames:
abs_path = os.path.join(dirpath, filename)
if filename.lower().endswith(".mp3"):
info = EasyID3(abs_path)
else:
info = MutagenFile(abs_path)
if info is None:
continue
title = "".join(info.get("title", "")).encode("utf-8")
artist = "".join(info.get("artist", "")).encode("utf-8")
try:
unicode_abs_path = unicode(abs_path.decode("utf-8"))
audio_file = AudioFile.select_cond("path = ?", (unicode_abs_path,)).next()
if os.stat(abs_path).st_mtime > audio_file.modtime:
audio_file.title = title
audio_file.artist = artist
audio_file.path = abs_path
audio_file.modtime = time.time()
print "Updated %s" % abs_path
except StopIteration:
audio_file = AudioFile.new(title=title, artist=artist, path=abs_path, modtime=time.time())
print "Added %s to database" % abs_path
示例4: write_info2file
def write_info2file(self, info):
# open file with mutagen
audio = File(info['filename'], easy=True)
if audio is None:
return
# write title+album information into audio files
if audio.tags is None:
audio.add_tags()
# write album+title
if info['album'] is not None:
audio.tags['album'] = info['album']
if info['title'] is not None:
audio.tags['title'] = info['title']
# write genre tag
if self.container.config.genre_tag is not None:
audio.tags['genre'] = self.container.config.genre_tag
else:
audio.tags['genre'] = ''
# write pubDate
if info['pubDate'] is not None:
audio.tags['date'] = info['pubDate']
audio.save()
示例5: TFileType
class TFileType(TestCase):
def setUp(self):
self.vorbis = File(os.path.join(DATA_DIR, "empty.ogg"))
fd, filename = mkstemp(".mp3")
os.close(fd)
shutil.copy(os.path.join(DATA_DIR, "xing.mp3"), filename)
self.mp3_notags = File(filename)
self.mp3_filename = filename
def tearDown(self):
os.remove(self.mp3_filename)
def test_delitem_not_there(self):
self.failUnlessRaises(KeyError, self.vorbis.__delitem__, "foobar")
def test_add_tags(self):
self.failUnlessRaises(NotImplementedError, FileType().add_tags)
def test_delitem(self):
self.vorbis["foobar"] = "quux"
del(self.vorbis["foobar"])
self.failIf("quux" in self.vorbis)
def test_save_no_tags(self):
self.assertTrue(self.mp3_notags.tags is None)
self.mp3_notags.save()
self.assertTrue(self.mp3_notags.tags is None)
示例6: TFileType
class TFileType(TestCase):
def setUp(self):
self.vorbis = File(os.path.join(DATA_DIR, "empty.ogg"))
filename = get_temp_copy(os.path.join(DATA_DIR, "xing.mp3"))
self.mp3_notags = File(filename)
self.mp3_filename = filename
def tearDown(self):
os.remove(self.mp3_filename)
def test_delitem_not_there(self):
self.failUnlessRaises(KeyError, self.vorbis.__delitem__, "foobar")
def test_add_tags(self):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
self.failUnlessRaises(NotImplementedError, FileType().add_tags)
def test_delitem(self):
self.vorbis["foobar"] = "quux"
del(self.vorbis["foobar"])
self.failIf("quux" in self.vorbis)
def test_save_no_tags(self):
self.assertTrue(self.mp3_notags.tags is None)
self.assertTrue(self.mp3_notags.filename)
self.mp3_notags.save()
self.assertTrue(self.mp3_notags.tags is None)
示例7: __init__
def __init__(self, path):
self.path = path
self.corrupt = False
self.bitrate = self.length = 0
self.title = self.artist = self.album = ''
try:
self.mimetype = subprocess.Popen([
"/usr/bin/file", "--mime-type", path],
stdout=subprocess.PIPE).communicate()[0].split(": ")[-1].rstrip()
except ValueError:
print(path)
av = self.mimetype[0:5] # enqueue any audio file
if av == "audio":
audio = MutagenFile( path, easy=True )
try: self.bitrate = int(audio.info.bitrate)
except: pass
try: self.length = int(audio.info.length)
except: pass
try:
self.artist = unicode( audio.get('artist', [''])[0] )
self.album = unicode( audio.get('album', [''])[0] )
self.title = unicode( audio.get('title', [''])[0] )
self.tracknumber = int( audio.get('tracknumber', [0])[0].split("/")[0] )
# split in above b/c sometimes encoders will list track numbers as "i/n"
except Exception, e:
print e, audio, audio.info.bitrate
示例8: getSongInfo
def getSongInfo(inputFile):
info = {}
# detect format and type of tags
file = File(inputFile)
"""
if 'APIC:' in file.keys():
artwork = file.tags['APIC:'].data # access APIC frame and grab the image
with open('./image.jpg', 'wb') as img:
img.write(artwork) # write artwork to new image
"""
# check for album art existence
if "APIC:" in file.keys():
artwork = file.tags["APIC:"].data # access APIC frame and grab the image
# extract image
info["image"] = artwork
# extract title
info["title"] = str(file["TIT2"][0])
# extract artist
info["artist"] = str(file["TPE1"][0])
# extract album
info["album"] = str(file["TALB"][0])
if "TDRC" in file.keys():
# extract year
info["year"] = str(file["TDRC"][0])
if "TCON" in file.keys():
# extract genre
info["genre"] = str(file["TCON"][0])
if "TPUB" in file.keys():
# extract publisher
info["publisher"] = str(file["TPUB"][0])
# extract length / duration
info["length"] = str(round(file.info.length / 60, 2))
return info
示例9: fixup_ID3
def fixup_ID3(fname: Union[str, MusicFileType]) -> None:
'''Convert RVA2 tags to TXXX:replaygain_* tags.
Argument should be an MusicFile (instance of mutagen.FileType) or
a string, which will be loaded by mutagen.MusicFile. If it is an
instance of mutagen.id3.ID3FileType, the ReplayGain information in
the RVA2 tags (if any) will be propagated to 'TXXX:replaygain_*'
tags. Thus the resulting file will have the ReplayGain information
encoded both ways for maximum compatibility.
If the track is an instance of 'mutagen.mp3.EasyMP3', it will be
re-opened as the non-easy equivalent, since EasyMP3 maps the
replaygain tags to RVA2, preventing the editing of the TXXX tags.
This function modifies the file on disk.
'''
# Make sure we have the non-easy variant.
if isinstance(fname, MusicFileType):
fname = fname.filename
track = MusicFile(fname, easy=False)
# Only operate on ID3
if not isinstance(track, id3.ID3FileType):
return
# Get the RVA2 frames
try:
track_rva2 = track['RVA2:track']
if track_rva2.channel != 1:
track_rva2 = None
except KeyError:
track_rva2 = None
try:
album_rva2 = track['RVA2:album']
if album_rva2.channel != 1:
album_rva2 = None
except KeyError:
album_rva2 = None
# Add the other tags based on RVA2 values
if track_rva2:
track['TXXX:replaygain_track_peak'] = \
id3.TXXX(encoding=id3.Encoding.UTF8,
desc='replaygain_track_peak',
text=format_peak(track_rva2.peak))
track['TXXX:replaygain_track_gain'] = \
id3.TXXX(encoding=id3.Encoding.UTF8,
desc='replaygain_track_gain',
text=format_gain(track_rva2.gain))
if album_rva2:
track['TXXX:replaygain_album_peak'] = \
id3.TXXX(encoding=id3.Encoding.UTF8,
desc='replaygain_album_peak',
text=format_peak(album_rva2.peak))
track['TXXX:replaygain_album_gain'] = \
id3.TXXX(encoding=id3.Encoding.UTF8,
desc='replaygain_album_gain',
text=format_gain(album_rva2.gain))
track.save()
示例10: set_tags
def set_tags(cls, audiobook, file_name):
tags = getattr(audiobook, "%s_tags" % cls.ext)['tags']
if not tags.get('flac_sha1'):
tags['flac_sha1'] = audiobook.get_source_sha1()
audio = File(file_name)
for k, v in tags.items():
audio[k] = v
audio.save()
示例11: get_artist_sort_title
def get_artist_sort_title(self):
try:
tags = MFile(self.filename, easy=True)
tag = tags.get('albumartistsort') # 'soaa'
if tag:
return tag[0]
return tags.get('artistsort')[0] # 'soar'
except:
return None
示例12: update_album_cover
def update_album_cover(filename, new_cover):
conf = get_or_create_config()
bak_conf = conf.copy()
song_album = ''
for album in bak_conf['library']:
for i, song in enumerate(bak_conf['library'][album]['songs']):
if song == filename:
song_album = album
image = Image.open(new_cover)
output = StringIO.StringIO()
image.save(output, format="JPEG")
data = output.getvalue()
output.close()
audio = File(filename)
audio.tags.add(
APIC(
encoding=3, # 3 is for utf-8
mime='image/jpeg', # image/jpeg or image/png
type=3, # 3 is for the cover image
desc=u'',
data=data
)
)
#from PyQt4.QtCore import pyqtRemoveInputHook
#pyqtRemoveInputHook()
#from IPython.Shell import IPShellEmbed; IPShellEmbed()()
audio.save()
break
if song_album:
break
covers = set()
for i, song in enumerate(bak_conf['library'][song_album]['songs']):
covers.add(get_full_song_info(song)[4])
if len(covers) == 1:
data = covers.pop()
#print data
if data: #all new cover are the same, updating album cover
song_file = File(filename)
album_name = get_cover_hash(song_file)
iconpath = os.path.join(ROOT_PATH,'cover_cache',album_name+'.png')
iconpath_jpg = os.path.join(ROOT_PATH,'cover_cache',album_name+'.jpg')
with open(iconpath_jpg, 'wb') as img:
img.write(data)
im = Image.open(iconpath_jpg)
#im = im.resize((cover_size, cover_size), Image.ANTIALIAS)
im.thumbnail((cover_size,cover_size), Image.ANTIALIAS)
im.save(iconpath)
try:
os.remove(iconpath_jpg)
except:
pass
conf['library'][song_album]['cover'] = getCoverArt(filename)[0]
save_config(conf)
示例13: postProcessSong
def postProcessSong(self, song):
if self.shouldGenerateTags:
try:
name = self.getSongPath(song)
localList = song.name.split("- ") #The song should be split as "artist - title". If not, it won't be recognized
artist = localList[0] if len(localList) > 1 else self.defaultArtist #The artist is usually first if its there. Otherwise no artist
if self.allSongsDefaultArtist: artist = self.defaultArtist
title = localList[1] if len(localList) > 1 else localList[0] #If there is no artist, the whole name is the title
artist = artist.lstrip().rstrip()
title = title.lstrip().rstrip()
#Appreciate this. It took upwards of 5 hours to get the damn software to do this.
try:
songID = EasyID3(name)
except ID3NoHeaderError:
songID = MutagenFile(name, easy = True)
songID.add_tags()
songID['artist'] = artist
songID['title'] = title
songID.save()
songID = ID3(name, v2_version=3) #EasyID3 doesn't support saving as 2.3 to get Windows to recognize it
songID.update_to_v23()
songID.save(v2_version=3)
except FileNotFoundError:
debug("File not found for: ", name)
示例14: read_from_file
def read_from_file(cls, file_path):
audio_file = File(file_path)
audio_type = type(audio_file)
if audio_type is MP3:
return cls(**{k: Metadata.flatten(v) for k, v in EasyID3(file_path).items()})
if audio_type is FLAC:
return cls(**{k: Metadata.flatten(v) for k, v in audio_file.items()})
raise UnknownFileFormatError('File %s does not seem to be a audio file' % file_path)
示例15: get_track_genres
def get_track_genres(self):
genre_list = []
try:
tags = MFile(self.filename)
genres = tags.get('\xa9gen')
if genres is not None and len(genres) > 0:
for genre in genres:
for sub_genre in parse_genres(genre):
genre_list.append(sub_genre.strip())
except Exception, e:
Log('Exception reading (genre): ' + str(e))