• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python mutagen.File类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中mutagen.File的典型用法代码示例。如果您正苦于以下问题:Python File类的具体用法?Python File怎么用?Python File使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了File类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:AzoresOne,项目名称:picard-plugins,代码行数:7,代码来源:save_and_rewrite_header.py


示例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()
开发者ID:daveystruijk,项目名称:music-library,代码行数:7,代码来源:analyze.py


示例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
开发者ID:daineX,项目名称:PyTTP,代码行数:28,代码来源:fetch_audio.py


示例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()
开发者ID:fk-lx,项目名称:gpodder,代码行数:27,代码来源:tagging.py


示例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)
开发者ID:akerbis,项目名称:mutagen,代码行数:29,代码来源:test___init__.py


示例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)
开发者ID:gdelfresno,项目名称:mutagen,代码行数:30,代码来源:test___init__.py


示例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
开发者ID:ViktorNova,项目名称:riddim,代码行数:29,代码来源:song.py


示例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
开发者ID:imsparsh,项目名称:Music-Fingerprinting-Lycaon,代码行数:35,代码来源:__init__.py


示例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()
开发者ID:DarwinAwardWinner,项目名称:rganalysis,代码行数:59,代码来源:fixup_id3.py


示例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()
开发者ID:fnp,项目名称:audio,代码行数:8,代码来源:tasks.py


示例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
开发者ID:dettwild,项目名称:LocalMedia.bundle,代码行数:9,代码来源:audiohelpers.py


示例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)
开发者ID:fabiomdiniz,项目名称:Frey,代码行数:56,代码来源:tanooki_library.py


示例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)
开发者ID:civilwargeeky,项目名称:MusicDownloader,代码行数:26,代码来源:MusicUpdater.py


示例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)        
开发者ID:lullis,项目名称:musika,代码行数:11,代码来源:base.py


示例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))
开发者ID:dettwild,项目名称:LocalMedia.bundle,代码行数:11,代码来源:audiohelpers.py


示例16: insert_coverart

    def insert_coverart(self):
        audio = File(self.filename)

        if self.cover.endswith('png'):
            cover_format = MP4Cover.FORMAT_PNG
        else:
            cover_format = MP4Cover.FORMAT_JPEG

        data = open(self.cover, 'rb').read()
        audio.tags['covr'] =  [MP4Cover(data, cover_format)]
        audio.save()
开发者ID:skysign,项目名称:gpodder,代码行数:11,代码来源:tagging.py


示例17: get_cover_art

def get_cover_art(song):
  if song.path == 'None':
    return None
  file = File(song.path)
  APIC = None
  for key in file.keys():
    if 'APIC:' in key:
      APIC = key
  if APIC is None:
    return None
  artwork = file.tags[APIC].data
  return artwork
开发者ID:mamins1376,项目名称:MPDroid-CoverServer,代码行数:12,代码来源:server.py


示例18: parse

 def parse(self):
     print os.path.abspath(self.filename)
     tag = MutagenFile(self.filename)
     if tag == None:
         print self.filename
     else:
         for key, value in tag.iteritems():
             if key in GENERAL_KEYS.keys():
                 self.dict[ GENERAL_KEYS[key] ] = unicode(value)
             elif key in MP3_KEYS.keys():
                 self.dict[ MP3_KEYS[key] ] = unicode(value)
             elif key in MP4_KEYS.keys():
                 self.dict[ MP4_KEYS[key] ] = unicode(value)
开发者ID:gsy,项目名称:gmusic,代码行数:13,代码来源:metadata.py


示例19: scan_track

def scan_track(path, from_dir = ''):
    t = None
    try:
        t = File(path)
    except Exception: pass
    if t is not None:
        if from_dir:
            t.relpath = t.filename.replace(from_dir, '', 1).lstrip('/')
            t.reldir = t.relpath.rsplit('/', 1)
            if len(t.reldir) > 1:
                t.reldir = t.reldir[0]
            else:
                t.reldir = ''
    return t
开发者ID:Unhelpful,项目名称:audiomangler,代码行数:14,代码来源:scanner.py


示例20: update_id3_tags

    def update_id3_tags(self):
        """
        Update ID3 tags of downloaded song
        """

        # Must init ID3 tags for appropriate header settings
        audio = File(self.tags._title+'.mp3', easy=True)
        audio.add_tags()

        # Save new tags
        audio['title'] = self.tags._title
        audio['artist'] = self.tags._artist
        audio['album'] = self.tags._album
        audio.save(self.tags._title+'.mp3')
开发者ID:nickatnight,项目名称:scgrab,代码行数:14,代码来源:scgrab.py



注:本文中的mutagen.File类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python _compat.cBytesIO函数代码示例发布时间:2022-05-27
下一篇:
Python mustache.render函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap