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


Python FLAC.get方法代码示例

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


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

示例1: flac_read

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

示例2: process_dir

# 需要导入模块: from mutagen.flac import FLAC [as 别名]
# 或者: from mutagen.flac.FLAC import get [as 别名]
def process_dir(out_list, directory, files):
    for f in files:
        path = os.path.join(directory, f)
        if os.path.isdir(path):
            return
        else:
            ext = f.split('.').pop().lower()
            metadata = {}
            if ext == 'mp3':
                metadata = EasyID3(path)
            elif ext == 'flac':
                metadata = FLAC(path)
            else:
                return
            out_data = {'tracknumber': metadata.get('tracknumber', ['0'])[0],
                        'title': metadata.get('title', ['Untitled'])[0],
                        'album': metadata.get('album', ['Untitled'])[0],
                        'artist': metadata.get('artist', ['Unknown'])[0],
                        'genre': metadata.get('genre', ['Unknown'])[0],
                        'date': metadata.get('date', ['Unknown'])[0],
                        'extension': ext,
                        'path': path}
            song_path = os.path.join(escape_path(out_data['artist']),
                                     escape_path(out_data['album']))
            song_name = "%02d-%s" % (int(out_data['tracknumber'].split('/')[0]),
                                     escape_path(out_data['title']))
            out_data['song_path'] = song_path
            out_data['song_name'] = song_name
            out_list.append(out_data)
开发者ID:bieber,项目名称:id3org,代码行数:31,代码来源:id3org.py

示例3: __song_flac

# 需要导入模块: from mutagen.flac import FLAC [as 别名]
# 或者: from mutagen.flac.FLAC import get [as 别名]
 def __song_flac(filename):
     f = FLAC(filename)
     artist = f.get("artist", ("",))[0]
     title = f.get("title", ("",))[0]
     rating = 0
     for k, v in f.iteritems():
         if k.startswith("rating"):
             rating = SongFiles.__adjust_rating_ogg(float(v[0]))
             break
     return Song(filename, artist, title, rating)
开发者ID:nickbp,项目名称:misc-utils,代码行数:12,代码来源:gmusic-ratings.py

示例4: find_inconsistent_tags

# 需要导入模块: from mutagen.flac import FLAC [as 别名]
# 或者: from mutagen.flac.FLAC import get [as 别名]
def find_inconsistent_tags(flac_filepaths, ignore_art=False, ignore_lyrics=False):
    """Look for missing data in FLAC 'id3' tags or tags that don't match the filename.

    Positional arguments:
    flac_filepaths -- list of FLAC file paths to read metadata from.

    Keyword arguments:
    ignore_art -- ignore checking if FLAC file has album art embedded in it, boolean.
    ignore_lyrics -- ignore checking if FLAC file has lyrics embedded in it, boolean.

    Returns:
    Dictionary with keys being FLAC file paths and values being a list of warnings to be printed about id3 tags.
    """
    tag_names = ['artist', 'date', 'album', 'tracknumber', 'title']
    messages = {p: [] for p in flac_filepaths}
    for path in flac_filepaths:
        # Verify filename.
        split = os.path.splitext(os.path.basename(path))[0].split(' - ')
        if len(split) != 5:
            messages[path].append("Filename doesn't have five items.")
            continue
        f_artist, f_date, f_album, f_track, f_title = split
        # Verify basic tags.
        try:
            tags = FLAC(path)
        except flac_error:
            messages[path].append('Invalid file.')
            continue
        t_artist, t_date, t_album, t_track, t_title = [tags.get(i, [''])[0] for i in tag_names]
        if f_artist != t_artist:
            messages[path].append('Artist mismatch: {} != {}'.format(f_artist, t_artist))
        if f_album != t_album:
            messages[path].append('Album mismatch: {} != {}'.format(f_album, t_album))
        if f_title != t_title:
            messages[path].append('Title mismatch: {} != {}'.format(f_title, t_title))
        # Verify numeric tags.
        if not f_date.isdigit():
            messages[path].append('Filename date not a number.')
        elif len(f_date) != 4:
            messages[path].append('Filename date not four digits.')
        elif f_date != t_date:
            messages[path].append('Date mismatch: {} != {}'.format(f_date, t_date))
        if not f_track.isdigit():
            messages[path].append('Filename track number not a number.')
        elif len(f_track) != 2:
            messages[path].append('Filename track number not two digits.')
        elif f_track != t_track:
            messages[path].append('Track number mismatch: {} != {}'.format(f_track, t_track))
        # Check for lyrics and album art.
        if not ignore_art and not tags.pictures:
            messages[path].append('No album art.')
        if not ignore_lyrics and not tags.get('unsyncedlyrics', [False])[0]:
            messages[path].append('No lyrics.')
    # Return dict of messages without empty lists.
    return {k: v for k, v in messages.items() if v}
开发者ID:Robpol86,项目名称:general,代码行数:57,代码来源:convert_music.py

示例5: __init__

# 需要导入模块: from mutagen.flac import FLAC [as 别名]
# 或者: from mutagen.flac.FLAC import get [as 别名]
class TagHandler:
    def __init__(self, filename, **kwargs):#artist=None, album=None, date=None, genre=None):
        self.tag = FLAC(filename)
        self.tags = {key:value for key, value in kwargs.iteritems() if value}
        self._convert_to_int()
    def _convert_to_int(self):
        for key, value in self.tags.iteritems():
            try:
                self.tags[key] = int(value)
            except:
                continue
    def prompt(self):
        for field in ['artist', 'title', 'date', 'album', 'tracknumber']:
            if not field in self.tags.keys():
                if self.tag.get(field, None):
                    self.tags[field] = self.tag[field][0]
                else:
                    print "Please provide a value for %s" % field
                    self.tags[field] = raw_input("> ")
        self._convert_to_int()
    def gen_lame(self):
        args = ('--ta|"%(artist)s"|--tt|"%(title)s"|--tl|"%(album)s"|--ty|"%(date)s"|--tn|"%(tracknumber)s"' % self.tags).split('|')
        if self.tags.get('genre', None):
            args += ['--tg', self.tags['genre']]
        return args
开发者ID:mcfitz2,项目名称:pybetterphp,代码行数:27,代码来源:TagHandler.py

示例6: __init__

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

示例7: check_flac_tags

# 需要导入模块: from mutagen.flac import FLAC [as 别名]
# 或者: from mutagen.flac.FLAC import get [as 别名]
def check_flac_tags(flac_path):
    flac = FLAC(flac_path)
    if not flac.get('artist'):
        raise Exception(u'Missing artist tag on {0}'.format(flac_path))
    if not flac.get('album'):
        raise Exception(u'Missing album tag on {0}'.format(flac_path))
    if not flac.get('title'):
        raise Exception(u'Missing title tag on {0}'.format(flac_path))

    track = flac.get('tracknumber') or flac.get('track')
    if type(track) in [str, unicode] and '/' in track:
        track = track.split('/')
    if type(track) is list:
        track = track[0]
    if not track:
        raise Exception(u'Missing track tag on {0}'.format(flac_path))

    disc = flac.get('discnumber') or flac.get('disc')
    if type(disc) in [str, unicode] and '/' in disc:
        disc = disc.split('/')
    if type(disc) is list:
        disc = disc[0]

    if disc:
        return disc, track
    else:
        return track,
开发者ID:ChaosTherum,项目名称:WhatManager2,代码行数:29,代码来源:utils.py

示例8: get_metadata

# 需要导入模块: from mutagen.flac import FLAC [as 别名]
# 或者: from mutagen.flac.FLAC import get [as 别名]
    def get_metadata(self):
        flac_stat = os.stat(self.flac_path)
        self.flac_current_mtime, self.flac_current_size = int(flac_stat.st_mtime), int(flac_stat.st_size)
        if os.path.exists(self.mp3_path):
            mp3_stat = os.stat(self.mp3_path)
            self.mp3_current_mtime, self.mp3_current_size = int(mp3_stat.st_mtime), int(mp3_stat.st_size)

        try:
            flac_tags = FLAC(self.flac_path)
        except flac_error:
            pass
        else:
            self.flac_artist = flac_tags.get('artist', [''])[0]
            self.flac_date = flac_tags.get('date', [''])[0]
            self.flac_album = flac_tags.get('album', [''])[0]
            self.flac_disc = flac_tags.get('discnumber', [''])[0]
            self.flac_track = flac_tags.get('tracknumber', [''])[0]
            self.flac_title = flac_tags.get('title', [''])[0]
            self.flac_has_lyrics = bool(flac_tags.get('unsyncedlyrics', [False])[0])
            self.flac_has_picture = bool(flac_tags.pictures)

        if not os.path.exists(self.mp3_path):
            return

        try:
            mp3_tags = ID3(self.mp3_path)
        except id3_error:
            pass
        else:
            stored_metadata = json.loads(getattr(mp3_tags.get("COMM::'eng'"), 'text', ['{}'])[0])
            self.flac_stored_mtime = stored_metadata.get('flac_mtime')
            self.flac_stored_size = stored_metadata.get('flac_size')
            self.mp3_stored_mtime = stored_metadata.get('mp3_mtime')
            self.mp3_stored_size = stored_metadata.get('mp3_size')
开发者ID:Robpol86,项目名称:general,代码行数:36,代码来源:convert_music.py

示例9: __init__

# 需要导入模块: from mutagen.flac import FLAC [as 别名]
# 或者: from mutagen.flac.FLAC import get [as 别名]
    def __init__(self, path):
        super(FLACFile, self).__init__(path)
        self.extension = "flac"

        media = FLAC(path)

        self.bitrate = media.info.total_samples * media.info.bits_per_sample / media.info.length
        self.length  = media.info.length

        self.metadata = {
            "artist": media.get( "artist", default=[None,] )[0],
            "album":  media.get( "album",  default=[None,] )[0],
            "title":  media.get( "title",  default=[None,] )[0],

            "genre":  media.get( "genre",  default=[None,] )[0],
            
            "trackno":  self.parse_no( media.get("tracknumber", default=["",])[0] ),
            "trackof":  self.parse_of( media.get("tracknumber", default=["",])[0] ),
            
            "diskno":  self.parse_no( media.get("disknumber", default=["",])[0] ),
            "diskof":  self.parse_of( media.get("disknumber", default=["",])[0] ),
        }
开发者ID:aweeks,项目名称:Music-Merge,代码行数:24,代码来源:mediafile.py

示例10: convert_file

# 需要导入模块: from mutagen.flac import FLAC [as 别名]
# 或者: from mutagen.flac.FLAC import get [as 别名]
    def convert_file(self, full_path):
        try:
            out_path = self.get_out_path(full_path)
            lame_options = self.lame_options or ['--preset', 'standard', '-h']

            metadata = FLAC(full_path)

            try:
                os.makedirs(os.path.dirname(out_path))
            except OSError as e:
                if e.errno != 17:
                    raise  # only raise if not "file exists" error

            flac_p = subprocess.Popen(
                [self.flac, '-s', '-d', '--stdout', full_path],
                stdout=subprocess.PIPE,
                preexec_fn=ignore_sigint)
            lame_cmd = [self.lame] + lame_options + ['--quiet', '-', out_path]
            lame_p = subprocess.Popen(lame_cmd,
                                      stdin=flac_p.stdout,
                                      preexec_fn=ignore_sigint)

            flac_p.wait()
            lame_p.wait()

            # now apply gain
            if self.apply_mp3gain:
                mp3gain_cmd = [self.mp3gain, '-q', '-T', '-r', '-k', out_path]

                subprocess.check_call(mp3gain_cmd,
                                      stdout=open('/dev/null', 'wb'))

            # finally, correct the tags
            id3data = File(out_path, easy=True)
            for attr in ('title', 'artist', 'album', 'date', 'genre',
                         'tracknumber'):
                id3data[attr] = metadata.get(attr)
            id3data.save()
        except Exception as e:
            status_queue.put(('ERROR', full_path, str(e)))
            if os.path.exists(out_path):
                os.unlink(out_path)
        else:
            status_queue.put(('OK', full_path, out_path))
开发者ID:mbr,项目名称:phonedown,代码行数:46,代码来源:phonedown.py

示例11: read_flac

# 需要导入模块: from mutagen.flac import FLAC [as 别名]
# 或者: from mutagen.flac.FLAC import get [as 别名]
def read_flac(filename):
    try:
        audio = FLAC(filename)
    except FLACNoHeaderError:
        return {}

    tags = {
        'filename' : filename,
        'artist' : audio.get('artist'),
        'album' : audio.get('album'),
        'track' : audio.get('tracknumber') or audio.get('track'),
        'title' : audio.get('title'),
        'date' : audio.get('date') or audio.get('year'),
    }

    # Mutagen returns lists for each tag so we have to pull out the actual string
    for tag in tags:
        if tags[tag]:
            tags[tag] = tags[tag][0]

    tags['channels'] = audio.info.channels

    return __normalize_tags(tags)
开发者ID:c2nes,项目名称:musicmanager,代码行数:25,代码来源:metadata.py

示例12: getAudioMetaData

# 需要导入模块: from mutagen.flac import FLAC [as 别名]
# 或者: from mutagen.flac.FLAC import get [as 别名]
def getAudioMetaData(service, ext):
	title = ""
	genre = ""
	artist = ""
	album = ""
	length = ""
	audio = None
	if fileExists("/tmp/.emcAudioTag.jpg"):
		os.remove("/tmp/.emcAudioTag.jpg")
	elif fileExists("/tmp/.emcAudioTag.png"):
		os.remove("/tmp/.emcAudioTag.png")
	elif fileExists("/tmp/.emcAudioTag.gif"):
		os.remove("/tmp/.emcAudioTag.gif")
	if service:
		path = service.getPath()
		if ext.lower() == ".mp3":
			try:
				audio = MP3(os.path.join(path), ID3 = EasyID3)
			except:
				audio = None
		elif ext.lower() == ".flac":
			try:
				audio = FLAC(os.path.join(path))
			except:
				audio = None
		elif ext.lower() == ".ogg":
			try:
				audio = OggVorbis(os.path.join(path))
			except:
				audio = None
		elif ext.lower() == ".mp4" or ext.lower() == ".m4a":
			try:
				audio = EasyMP4(os.path.join(path))
			except:
				audio = None
		# first for older mutagen-package(under 1.27)
		# APEv2 is tagged from tools like "mp3tag"
		# no tagging in new mutagen.aac
		elif ext.lower() == ".aac":
			try:
				audio = APEv2File(os.path.join(path))
			except:
				audio = None
		if audio:
			if ext.lower() != ".aac":
				length = str(datetime.timedelta(seconds=int(audio.info.length)))
			else:
				if isMutagenAAC:
					getlength = AAC(os.path.join(path))
					length = str(datetime.timedelta(seconds=int(getlength.info.length)))
				else:
					length = str(datetime.timedelta(seconds=int(audio._Info.length)))
			title = audio.get('title', [service.getPath()])[0]
			try:
				genre = audio.get('genre', [''])[0]
			except:
				genre = ""
			artist = audio.get('artist', [''])[0]
			album = audio.get('album', [''])[0]
			# now we try to get embedded covers
			if ext.lower() == ".mp3":
				try:
					scover = ID3(service.getPath())
				except:
					scover = None
				if scover:
					scovers = scover.getall("APIC")
					if len(scovers) > 0:
						try:
							ext = "." + scovers[0].mime.lower().split("/", -1)[1]
							writeTmpCover(scovers[0].data, ext)
						except Exception, e:
							emcDebugOut("[EMCMutagenSupport] Exception in Mp3EmbeddedCover: " + str(e))
			elif ext.lower() == ".flac":
				try:
                                	scover = audio.pictures
				except:
					scover = None
				if scover:
					if scover[0].data:
						try:
							ext = "." + scover[0].mime.lower().split("/", -1)[1]
							writeTmpCover(scover[0].data, ext)
						except Exception, e:
							emcDebugOut("[EMCMutagenSupport] Exception in FlacEmbeddedCover: " + str(e))
			elif ext.lower() == ".ogg":
				try:
                                	scover = audio
				except:
					scover = None
				if scover:
					for b64_data in scover.get("metadata_block_picture", []):
						try:
							data = base64.b64decode(b64_data)
						except (TypeError, ValueError):
							continue

						try:
							picture = Picture(data)
						except FLACError:
#.........这里部分代码省略.........
开发者ID:CBR900Biker,项目名称:e2openplugin-EnhancedMovieCenter,代码行数:103,代码来源:MutagenSupport.py

示例13: getSongTags

# 需要导入模块: from mutagen.flac import FLAC [as 别名]
# 或者: from mutagen.flac.FLAC import get [as 别名]
def getSongTags(file):
    # Get the actual ID3 tags for music songs as the server is lacking that info
    rating = 0
    comment = ""
    hasEmbeddedCover = False
    
    isTemp,filename = getRealFileName(file)
    log.info( "getting song ID3 tags for " + filename)
    
    try:
        ###### FLAC FILES #############
        if filename.lower().endswith(".flac"):
            audio = FLAC(filename)
            if audio.get("comment"):
                comment = audio.get("comment")[0]
            for pic in audio.pictures:
                if pic.type == 3 and pic.data:
                    #the file has an embedded cover
                    hasEmbeddedCover = True
                    break
            if audio.get("rating"):
                rating = float(audio.get("rating")[0])
                #flac rating is 0-100 and needs to be converted to 0-5 range
                if rating > 5: rating = (rating / 100) * 5
        
        ###### MP3 FILES #############
        elif filename.lower().endswith(".mp3"):
            audio = ID3(filename)
            
            if audio.get("APIC:Front Cover"):
                if audio.get("APIC:Front Cover").data:
                    hasEmbeddedCover = True
            
            if audio.get("comment"):
                comment = audio.get("comment")[0]
            if audio.get("POPM:Windows Media Player 9 Series"):
                if audio.get("POPM:Windows Media Player 9 Series").rating:
                    rating = float(audio.get("POPM:Windows Media Player 9 Series").rating)
                    #POPM rating is 0-255 and needs to be converted to 0-5 range
                    if rating > 5: rating = (rating / 255) * 5
        else:
            log.info( "Not supported fileformat or unable to access file: %s" %(filename))
        
        #the rating must be a round value
        rating = int(round(rating,0))
    
    except Exception as e:
        #file in use ?
        log.error("Exception in getSongTags %s" % e)
        rating = None
    
    #remove tempfile if needed....
    if isTemp: xbmcvfs.delete(filename)
        
    return (rating, comment, hasEmbeddedCover)
开发者ID:kravone,项目名称:plugin.video.emby,代码行数:57,代码来源:musicutils.py


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