当前位置: 首页>>代码示例>>Python>>正文


Python File.get方法代码示例

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


在下文中一共展示了File.get方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: fetch_metadata

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import get [as 别名]
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,代码行数:30,代码来源:fetch_audio.py

示例2: __init__

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import get [as 别名]
    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,代码行数:31,代码来源:song.py

示例3: Tag

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import get [as 别名]
class Tag(object):
    def __init__(self, filename):
        self.tags = File(filename, easy=True)
        if self.tags == None:
            raise TagTypeError()

    @property
    def album(self):
        return self.tags.get('album')

    @album.setter
    def album(self, value):
        self.tags['album'] = value

    @album.deleter
    def album(self):
        del self.tags['album']

    @property
    def artist(self):
        return self.tags.get('artist')

    @artist.setter
    def artist(self, value):
        self.tags['artist'] = value

    @artist.deleter
    def artist(self):
        del self.tags['artist']


    @property
    def title(self):
        return self.tags.get('title')

    @title.setter
    def title(self, value):
        self.tags['title'] = value

    @title.deleter
    def title(self):
        del self.tags['title']


    @property
    def track(self):
        return self.tags.get('tracknumber')

    @track.setter
    def track(self, value):
        self.tags['tracknumber'] = value

    @track.deleter
    def track(self):
        del self.tags['tracknumber']

    def save(self):
        self.tags.save();
开发者ID:terrasea,项目名称:music-file-tag-tree-sorter,代码行数:60,代码来源:tag.py

示例4: get_artist_sort_title

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import get [as 别名]
 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,代码行数:11,代码来源:audiohelpers.py

示例5: process_files

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import get [as 别名]
def process_files(path, stats):
  """
  Recurse down directory path and process each audio file.
  """
  counter = 0
  for root, dirs, files in os.walk(path):
    for f in files:
      # We maintain a counter to keep file names unique
      counter += 1
      stats.files_read += 1
      filename = os.path.join(root, f)

      try:
        audio = File(filename, easy=True)
      except Exception, e:
        stats.add_type_failure(filename)
        continue

      if not audio:
        stats.add_parse_failure(filename)
        continue

      test_tags = ['artist', 'album', 'title']
      missing_tags = []

      for tag in test_tags:
        if not audio.has_key(tag):
          missing_tags.append(tag)

      tracknumber = audio.get('tracknumber', [None])[0]
      artist = sanitize_path(audio.get('artist', ['No Artist'])[0])
      album = sanitize_path(audio.get('album', ['No Album'])[0])
      title = sanitize_path(audio.get('title', ["%d_%s" % (counter, f)])[0])

      if tracknumber:
        try:
          tracknumber = int(re.sub(r'.*?(\d+).*', r'\1', tracknumber))
        except ValueError, e:
          tracknumber = None
          pass

      (_, extension) = os.path.splitext(filename)

      if not tracknumber:
        newname = os.path.join(artist, album, title + extension)
      else:
        newname = os.path.join(
            artist, album, "%02d - %s%s" % (tracknumber, title, extension))

      if len(missing_tags) > 0:
        pretty_missing_tags = str.join(", ", missing_tags)
        stats.add_missing_tag_failure(
            filename + ": " + pretty_missing_tags,
            newname)

      stats.add_track(filename, newname, artist, album, tracknumber, title)
开发者ID:0xfe,项目名称:mp3renamer,代码行数:58,代码来源:mp3renamer.py

示例6: run

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import get [as 别名]
    def run(self):
        while not self.__was_stopped:
            if self.downloader is not None and self.downloader.ended:
                f = File(self.downloader.downloaded_path(), easy=True)
                if not re.search('[a-zA-Z0-9]', self.queue[0].artist):
                    if re.search('[a-zA-Z0-9]', f.get("artist", "")):
                        self.queue[0].artist = f["artist"]
                    else:
                        self.queue[0].artist = "Unknown"
                        f["artist"] = self.queue[0].artist
                else:
                    f["artist"] = self.queue[0].artist
                if not re.search('[a-zA-Z0-9]', self.queue[0].album):
                    if re.search('[a-zA-Z0-9]', f.get("album", "")):
                        self.queue[0].album = f["album"]
                    else:
                        self.queue[0].album = "Unknown"
                        f["album"] = self.queue[0].album
                else:
                    f["album"] = self.queue[0].album
                if not re.search('[a-zA-Z0-9]', self.queue[0].track):
                    if re.search('[a-zA-Z0-9]', f.get("title", "")):
                        self.queue[0].track = f["title"]
                    else:
                        self.queue[0].track = join(self.downloader.downloaded_path().split("/")[-1].split(".")[0:-1],
                                                   '.')
                        f["title"] = self.queue[0].track
                else:
                    f["title"] = self.queue[0].track
                print f.tags
                f.save()

                target_dir = join([config.download_path,
                                   safe_filename(self.queue[0].artist),
                                   safe_filename(self.queue[0].album)], "/")
                if not os.path.exists(target_dir):
                    os.makedirs(target_dir)
                file_path = target_dir + "/" + safe_filename(self.queue[0].track) + "_" + random_string() + "." + \
                    self.downloader.downloaded_path().split(".")[-1]
                shutil.move(self.downloader.downloaded_path(), file_path)
                library.add_track(TrackInfo(file_path))
                del self.queue[0]
                self.downloader = None
                if len(self.queue) > 0:
                    self.start_download()
            time.sleep(1)
开发者ID:mRokita,项目名称:sMusic-core,代码行数:48,代码来源:download_controller.py

示例7: get_track_genres

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import get [as 别名]
 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,代码行数:13,代码来源:audiohelpers.py

示例8: process_metadata

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import get [as 别名]
  def process_metadata(self, metadata):

    Log('Reading OGG tags from: ' + self.filename)
    try: 
      tags = MFile(self.filename)
      Log('Found tags: ' + str(tags.keys()))
    except:
      Log('An error occured while attempting to parse the OGG file: ' + self.filename)
      return

    # Genres
    try:
      genres = tags.get('genre')
      if genres is not None and len(genres) > 0:
        metadata.genres.clear()
        for genre in genres:
          for sub_genre in parse_genres(genre):
            metadata.genres.add(sub_genre.strip())
    except Exception, e:
      Log('Exception reading genre: ' + str(e))
开发者ID:kmoore134,项目名称:plexmediaserver-freebsd-10.1-amd64,代码行数:22,代码来源:audiohelpers.py

示例9: get_new_path

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import get [as 别名]
def get_new_path(source, target):

    filename = os.path.basename(source).decode("utf-8")

    f = File(source)
    if f is None:
        raise UnsupportedFileType(source)

    if isinstance(f, mutagen.mp4.MP4):
        KeyMap = Mp4KeyMap
    else:
        KeyMap = Id3KeyMap

    try:
        artist = f[KeyMap.albumartist][0]
    except KeyError:
        try:
            artist = f[KeyMap.artist][0]
        except KeyError:
            artist = u"Unknown Artist"

    if f.get(KeyMap.compilation, None):
        artist = "Compilations"

    try:
        album = f[KeyMap.album][0]
    except KeyError:
        album = u"Unknown Album"

    base = os.path.join(target, artist, album)

    try:
        os.makedirs(base)
    except OSError:
        pass

    new_file_name = _get_file_name(base, filename)
    new_path = os.path.join(base, new_file_name)
    vprint("new file path: %s" % new_path)

    return os.path.normpath(new_path)
开发者ID:rupa108,项目名称:audiosort,代码行数:43,代码来源:audiosort.py

示例10: process_metadata

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import get [as 别名]
    def process_metadata(self, metadata):

        Log("Reading FLAC tags from: " + self.filename)
        try:
            tags = MFile(self.filename)
            Log("Found tags: " + str(tags.keys()))
        except:
            Log("An error occurred while attempting to parse the FLAC file: " + self.filename)
            return

        # Genres
        try:
            genres = tags.get("genre")
            if genres is not None and len(genres) > 0:
                metadata.genres.clear()
                for genre in genres:
                    for sub_genre in parse_genres(genre):
                        if sub_genre.strip():
                            metadata.genres.add(sub_genre.strip())
        except Exception, e:
            Log("Exception reading genre: " + str(e))
开发者ID:TGVarik,项目名称:LocalMedia.bundle,代码行数:23,代码来源:audiohelpers.py

示例11: get_album_sort_title

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import get [as 别名]
 def get_album_sort_title(self):
   try:
     tags = MFile(self.filename, easy=True)
     return tags.get('albumsort')[0]  # 'soal'
   except:      
     return None
开发者ID:dettwild,项目名称:LocalMedia.bundle,代码行数:8,代码来源:audiohelpers.py

示例12: get_track_sort_title

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import get [as 别名]
 def get_track_sort_title(self):
   try:
     tags = MFile(self.filename, easy=True)
     return tags.get('titlesort')[0]  # 'sonm'
   except:      
     return None
开发者ID:dettwild,项目名称:LocalMedia.bundle,代码行数:8,代码来源:audiohelpers.py

示例13: get_artist_sort_title

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import get [as 别名]
 def get_artist_sort_title(self):
   try:
     tags = MFile(self.filename, easy=True)
     return tags.get('artistsort')[0]  # 'soar'
   except:      
     return None
开发者ID:pannal,项目名称:LocalMediaExtended.bundle,代码行数:8,代码来源:audiohelpers.py

示例14: Songinfo

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import get [as 别名]
class Songinfo(dict):
    TAG_TRANSLATE = {
        'title': ('TIT2',),
        'artist': ('TPE1', 'TPE2',),
        'album': ('TALB',),
    }

    def __init__(self, filename):
        self._filename = filename
        self._match = None
        dict.__init__(self)

    def __str__(self):
        artist = self.get('artist', _("Unknown Artist"))
        title = self.get('title', _("Unknown Title"))
        return "%s - %s" % (artist, title)

    def fetch_info(self, optional=('album',)):
        """
        Check the file type and call the corresponding method to get
        title info :-)
        """
        self._audio = MutagenFile(self._filename)

        required = ('artist', 'title')

        info = {
            'length': (int(self._audio.info.length)
                       if self._audio.info.length else 0),
        }

        for tag in required + optional:
            try:
                info[tag] = self.get_taginfo(tag)
            except TitleNotFound:
                if tag in optional:
                    continue
                raise

        self.update(info)

    def get_alternative_tag(self, tags):
        for tag in tags:
            item = self._audio.get(tag, None)
            if item and isinstance(item, list):
                return item[0]
            elif item:
                return item

        return None

    def get_from_fname(self, what):
        if self._match is not None:
            match = self._match
        else:
            try:
                parser = FilenameParser(self._filename)
                match = parser.parse()
            except LookupError:
                raise TitleNotFound(self._filename)

        if match:
            self._match = match
            try:
                return match[what]
            except KeyError:
                pass

        raise TitleNotFound(self._filename)

    def get_taginfo(self, what):
        item = self._audio.get(what, None)
        if item and isinstance(item, list):
            return item[0]
        elif not item and what in self.TAG_TRANSLATE:
            item = self.get_alternative_tag(self.TAG_TRANSLATE[what])
            if not item:
                item = self.get_from_fname(what)
                if item:
                    return item
            else:
                return item
        elif item:
            return item
        else:
            item = self.get_from_fname(what)
            if item:
                return item

        raise TitleNotFound(self._filename)
开发者ID:aszlig,项目名称:LastWatch,代码行数:92,代码来源:lastwatch.py


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