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

Python flac.FLAC类代码示例

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

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



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

示例1: test_two_invalid

def test_two_invalid(tmpdir):
    """Test when two FLAC files have invalid tags."""
    flac_dir = tmpdir.mkdir('flac')
    flac_files = []
    # One.
    flac = flac_dir.join('Artist2 - 202 - Album - 01 - Title.flac').ensure(file=True)
    with open(os.path.join(os.path.dirname(__file__), '1khz_sine.flac'), 'rb') as f:
        flac.write(f.read(), 'wb')
    tags = FLAC(str(flac.realpath()))
    tags.update(dict(artist='Artist2', date='2012', album='Album', tracknumber='01', title='Title'))
    tags.save()
    flac_files.append(str(flac.realpath()))
    # Two.
    flac = flac_dir.join('Artist - 2014 - Album - 01 - Title.flac').ensure(file=True)
    with open(os.path.join(os.path.dirname(__file__), '1khz_sine.flac'), 'rb') as f:
        flac.write(f.read(), 'wb')
    tags = FLAC(str(flac.realpath()))
    tags.update(dict(artist='Artist2', date='2014', album='Album', tracknumber='01', title='Title'))
    tags.save()
    flac_files.append(str(flac.realpath()))
    # Test.
    a_messages = find_inconsistent_tags(flac_files, True, True)
    e_messages = {
        flac_files[0]: ["Filename date not four digits."],
        flac_files[1]: ["Artist mismatch: Artist != Artist2"],
    }
    assert e_messages == a_messages
开发者ID:Robpol86,项目名称:general,代码行数:27,代码来源:test_find_inconsistent_tags.py


示例2: test_one_valid_two_invalid

def test_one_valid_two_invalid(tmpdir):
    """Test when one FLAC file is fully valid and another one isn't."""
    flac_dir = tmpdir.mkdir('flac')
    flac_files = []
    # Valid.
    flac = flac_dir.join('Artist2 - 2012 - Album - 01 - Title.flac').ensure(file=True)
    with open(os.path.join(os.path.dirname(__file__), '1khz_sine.flac'), 'rb') as f:
        flac.write(f.read(), 'wb')
    tags = FLAC(str(flac.realpath()))
    tags.update(dict(artist='Artist2', date='2012', album='Album', tracknumber='01', title='Title'))
    tags.save()
    flac_files.append(str(flac.realpath()))
    # Invalid.
    flac = flac_dir.join('Artist - 2014 - Album - 01 - Title.flac').ensure(file=True)
    with open(os.path.join(os.path.dirname(__file__), '1khz_sine.flac'), 'rb') as f:
        flac.write(f.read(), 'wb')
    tags = FLAC(str(flac.realpath()))
    tags.update(dict(artist='Artist2', date='2014', album='Album', tracknumber='01', title='Title'))
    tags.save()
    flac_files.append(str(flac.realpath()))
    # Test.
    a_messages = find_inconsistent_tags(flac_files, True, True)
    e_messages = {flac_files[1]: [
        "Artist mismatch: Artist != Artist2",
    ]}
    assert e_messages == a_messages
开发者ID:Robpol86,项目名称:general,代码行数:26,代码来源:test_find_inconsistent_tags.py


示例3: __init__

class Id3tool:
    ''' class to read/write mp3 tags '''

    def __init__(self, fn):
        ''' allow throw if file not supported '''

        if fnmatch.fnmatch(fn, '*.ogg'):
            self.tag_obj = OggVorbis(fn)

        elif fnmatch.fnmatch(fn, '*.flac'):
            self.tag_obj = FLAC(fn)

        else:
            self.tag_obj = EasyID3(fn)

    def save(self):
        self.tag_obj.save()

    def readTag(self, tag):
        if self.tag_obj:
            tmp = self.tag_obj.get(unicode(tag))
            return tmp[0] if tmp else  ''
        else:
            return ''

    def writeTag(self, tag, val):
        self.tag_obj[unicode(tag)] = unicode(val)
开发者ID:jonnyboy,项目名称:mp3scrub,代码行数:27,代码来源:fileio.py


示例4: main

def main(args):
    """
    """
    # This is nonsense, don't need to pass that argument twice
    scanner = scan.Scanner()

    if not scanner.scan_album(args.album):
        sys.stderr.write('Invalid Album!\n')
        sys.exit(1)

    # Construct an album representation
    # (This function will be moved to the lib)
    m = const.REGEX_ALBUM_FOLDER.match(args.album).groupdict()
    if not m:
        # A bit reduntant, but better safe than sorry
        sys.stderr.write("Could not read album folder\n")
        sys.exit(1)

    files = map(lambda fn: os.path.join(args.album, fn),
                sorted(filter(const.REGEX_TRACK_FILENAME.match,
                              os.listdir(args.album)
                       )
                )
    )
    show = ''
    for fn in files:
        audio = FLAC(fn)
        # Maybe create a util function for this purpose
        audio_dict = dict([(k,v[0]) for k,v in audio.items()])
        show += TPL_TRACK_SHOW.format(**audio_dict)
    head = TPL_ALBUM_SHOW.format(**audio_dict)
    show = head + TPL_SEPARATOR(len(head)-1) + show
    print show.strip('\n')
开发者ID:rseed42,项目名称:music-collection-tools,代码行数:33,代码来源:__init__.py


示例5: getsubmission

def getsubmission(tfile):
    data = open(tfile).read()
    torrent = decode(data)
    tname = torrent['info']['name']

    for file in torrent["info"]["files"]:
        name = "/".join(file["path"])
        flac_re = re.compile(".flac")
        if flac_re.search(name) != None:
            flacname=name
            log_re = re.compile(".log")
        if log_re.search(name) !=None:
            logname=name
    
    fpath = os.path.join(tname,flacname)
    lpath = os.path.join(tname,logname)

    audio = FLAC(fpath)
    print audio.keys()
    if not audio.has_key('musicbrainz_albumid'):
        print "ReleaseID tag is not set. Has this flac been tagged by picard?"
        return(-1)

    albumid = audio['musicbrainz_albumid'][0]
    print albumid

    q = ws.Query()
    try:
        inc = ws.ReleaseIncludes(artist=True, releaseEvents=True, labels=True,
                                 discs=True, tracks=True)
        release = q.getReleaseById(albumid, inc)
    except ws.WebServiceError, e:
        print 'Error:', e
        return(-1)
开发者ID:bh0085,项目名称:programming,代码行数:34,代码来源:what_mb.py


示例6: setImage

	def setImage(self, song):
		audio = FLAC(song.get("~filename", ""))
		if len(self.imgFiles) <= 0:
			return

		for p in self.imgFiles:
			try:
				audio.add_picture(p)
			except:
				printError()
				return False
		audio.save()
		## and now count the images
		count = "0"
		## if file has no images -> set to 0
		if (audio.pictures is None) or (len(audio.pictures) <= 0):
			pass
		else:
			count = str(len(audio.pictures))

		if not "pictures" in song:
			song["pictures"] = count

		if song["pictures"] <> count:
			song["pictures"] = count
		app.window.emit("artwork-changed", [song])
		return
开发者ID:claw-strophobic,项目名称:dacapo,代码行数:27,代码来源:addImage.py


示例7: FlacStripper

class FlacStripper(MutagenStripper):
    """ Represent a Flac audio file
    """
    def _create_mfile(self):
        self.mfile = FLAC(self.filename)

    def remove_all(self):
        """ Remove the "metadata" block from the file
        """
        super(FlacStripper, self).remove_all()
        self.mfile.clear_pictures()
        self.mfile.save()
        return True

    def is_clean(self):
        """ Check if the "metadata" block is present in the file
        """
        return super(FlacStripper, self).is_clean() and not self.mfile.pictures

    def get_meta(self):
        """ Return the content of the metadata block if present
        """
        metadata = super(FlacStripper, self).get_meta()
        if self.mfile.pictures:
            metadata['picture:'] = 'yes'
        return metadata
开发者ID:murinicanor,项目名称:MAT,代码行数:26,代码来源:mutagenstripper.py


示例8: setSortTags

def setSortTags(path):
    ext = os.path.splitext(path)[1].lower()
    meta = None

    try:
        if ext == '.mp3':
            meta = MP3(path)
        elif ext == '.m4a':
            meta = MP4(path)
        elif ext == '.flac':
            meta = FLAC(path)
        else:
            return
    except:
        pass

    if meta:
        tagsToProcess = ('ALBUM', 'ALBUMARTIST', 'ARTIST', 'TITLE')
        save = False
        try:
            for tag in tagsToProcess:
                processed = checkTagMakeSort(path, meta, tag)
                if (processed):
                    save = True
            if save:
                meta.save()
        except:
            pass
开发者ID:twotreeszf,项目名称:Sony-Walkman-Sorter,代码行数:28,代码来源:SortFilesForce.py


示例9: write_field

  def write_field(self, file, field, value, bypassdbwrite=False):
    filename, extension = os.path.splitext(file)
    if extension.upper() == '.MP3':
      # Try to open the ID3 tags
      try:
        audio = ID3(file)
      except mutagen.id3.ID3NoHeaderError:
        # Save a blank ID3 header first
        audio = ID3()
      id3field = self.MAP_ID3_FIELDS[field]
      fieldtype, unused, fieldname = id3field.partition(':')
      gentag = getattr(mutagen.id3, fieldtype)
      audio[id3field] = gentag(encoding=3, desc=u'%s' % fieldname, text=value)
      #audio['TXXX:TAG'] = TXXX(encoding=3, desc=u'TAG', text=tags)
    elif extension.upper() == '.FLAC':
      audio = FLAC(file)
      audio[self.MAP_FLAC_FIELDS[field]] = value
    audio.save(file)
    print "[LIBRARY] Field '%s' written in file %s" % (field, os.path.basename(file))

    # Update DB if needed
    if file in self.map_track_info:
      self.map_track_info[file][field] = value
      if not bypassdbwrite:
        self.save_database()
开发者ID:corradio,项目名称:pingweeplayer,代码行数:25,代码来源:library.py


示例10: set_image

    def set_image(self, image):
        """Replaces all embedded images by the passed image"""

        with translate_errors():
            tag = FLAC(self["~filename"])

        try:
            data = image.read()
        except EnvironmentError as e:
            raise AudioFileError(e)

        pic = Picture()
        pic.data = data
        pic.type = APICType.COVER_FRONT
        pic.mime = image.mime_type
        pic.width = image.width
        pic.height = image.height
        pic.depth = image.color_depth

        tag.add_picture(pic)

        with translate_errors():
            tag.save()

        # clear vcomment tags
        super(FLACFile, self).clear_images()

        self.has_images = True
开发者ID:zsau,项目名称:quodlibet,代码行数:28,代码来源:xiph.py


示例11: test_delete_multiple

 def test_delete_multiple(self):
     # on delete we delete both
     f = FLAC(self.filename)
     f.delete()
     assert len(f.tags) == 0
     f = FLAC(self.filename)
     assert f.tags is None
开发者ID:quodlibet,项目名称:mutagen,代码行数:7,代码来源:test_flac.py


示例12: flac_read

def flac_read(fpath):
    audio = FLAC(fpath)
    return uni({
        'artist': audio.get('artist', [None])[0],
        'album': audio.get('album', [None])[0],
        'title': audio.get('title', [None])[0]
        })
开发者ID:jbenito3,项目名称:radiocrepe,代码行数:7,代码来源:metadata.py


示例13: test_force_shrink

 def test_force_shrink(self):
     self.test_force_grow()
     f = FLAC(self.NEW)
     f["faketag"] = "foo"
     f.save()
     f = FLAC(self.NEW)
     self.failUnlessEqual(f["faketag"], ["foo"])
开发者ID:andrewboie,项目名称:discogstool,代码行数:7,代码来源:test_flac.py


示例14: test_largest_valid

 def test_largest_valid(self):
     f = FLAC(self.filename)
     pic = Picture()
     pic.data = b"\x00" * (2 ** 24 - 1 - 32)
     self.assertEqual(len(pic.write()), 2 ** 24 - 1)
     f.add_picture(pic)
     f.save()
开发者ID:quodlibet,项目名称:mutagen,代码行数:7,代码来源:test_flac.py


示例15: check_flac_tags

def check_flac_tags(full_path, e):

    t = {} # "proper" tags

    tags = FLAC(full_path)

    unallowed = set(tags.keys()).difference(flac_allow)

    if unallowed:
        for item in unallowed:
            e.append("Unallowed tag: '" + item + "' - remove")

    # "minimal" tags
    for item in 'album', 'tracknumber', 'title', 'date':
        t[item] = tags[item][0]

    # Handle multiple artist tags in single track
    if len(tags['artist']) > 1:
        t['artist'] = ", ".join(tags['artist'])
    else:
        t['artist'] = tags['artist'][0]

    # "optional" tags
    for item in 'tracktotal', 'genre', 'albumartist', 'discnumber', 'disctotal':
        if item in tags:
            t[item] = tags[item][0]
        else:
            t[item] = None

    return t, e
开发者ID:jaquer,项目名称:AudioRenamer,代码行数:30,代码来源:AudioRenamer.py


示例16: _loadTags

	def _loadTags(self):
		try:
			audio = FLAC()
			audio.load(self.uri)
			return audio.tags
		except Exception, e:
			return None
开发者ID:Torf,项目名称:Pycogs,代码行数:7,代码来源:folder_object.py


示例17: tag

 def tag(self):
     if self.type == 'Free Lossless Audio Codec':
         f = FLAC(self.name)
         tags = CUE_META.flac_tags(self.track_nr)
         for t in tags[0]:
             f[t] = tags[0][t]
         f.save()
开发者ID:DiGiTaLAnGeL92,项目名称:headphones,代码行数:7,代码来源:cuesplit.py


示例18: media_info

def media_info(f):
    aid_re = re.compile("brainz.*album.*id",re.I)
    has_info = 0
    ext = os.path.splitext(f)[-1]
    if ext == ".mp3":
        has_info = 1
        info = ID3(f)
        format = "MP3"
    if ext == ".flac":
        has_info = 1
        info = FLAC(f)
        format = "FLAC"
    if ext == ".ogg":
        has_info = 1
        info = OggVorbis(f)
        format = "OGG"

    if not has_info:
        return {}
    for k in info.keys():
        if re.search(aid_re,k) != None:
            aid = info[k]
            if type(aid) ==mutagen.id3.TXXX:
                aid = aid.__unicode__()
            if type(aid) == type([0]):
                aid = aid[0]
    
    info_d = {}
    info_d['mbid'] = aid
    return info_d
开发者ID:bh0085,项目名称:programming,代码行数:30,代码来源:catalog.py


示例19: write_genre

 def write_genre(self, file_path, file_ext, genre):
     '''write genre to a single file'''
     if file_ext == '.flac':
         tag = FLAC(file_path)
     elif file_ext == '.mp3':
         tag = EasyID3(file_path)
     tag['genre'] = genre
     tag.save()
开发者ID:brokkr,项目名称:pythonjunk,代码行数:8,代码来源:harmonize_genre_tag.py


示例20: test_write_reread

 def test_write_reread(self):
     flac = FLAC(self.NEW)
     del(flac["artist"])
     flac.save()
     flac2 = FLAC(self.NEW)
     self.failUnlessEqual(flac["title"], flac2["title"])
     data = open(self.NEW, "rb").read(1024)
     self.failIf("Tunng" in data)
开发者ID:andrewboie,项目名称:discogstool,代码行数:8,代码来源:test_flac.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python flac.MetadataBlock类代码示例发布时间:2022-05-27
下一篇:
Python flac.to_int_be函数代码示例发布时间: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