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


Python mp3.MP3属性代码示例

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


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

示例1: run

# 需要导入模块: from mutagen import mp3 [as 别名]
# 或者: from mutagen.mp3 import MP3 [as 别名]
def run(self):
        if os.path.isfile(DOWNLOAD_LIST):
            s = read_from_file(DOWNLOAD_LIST)
            search_list = s.split('\n')
            for list in search_list:
                if list != '':
                    splitlist = list.split('<>')
                    filename = os.path.join(splitlist[0], splitlist[4])
                    artist = splitlist[1]
                    album = splitlist[2]
                    track = splitlist[3]
                    trackname = splitlist[4]
                    tracktitle = trackname
                    if os.path.exists(filename):
                        audio = MP3(filename, ID3=EasyID3)
                        audio["title"] = tracktitle
                        audio["artist"] = artist
                        audio["album"] = album
                        audio["tracknumber"] = track
                        audio.save()
                        remove_from_list(list, DOWNLOAD_LIST)
        notification('Music Library', 'ID3 tags updated', '3000', iconart)
        xbmc.executebuiltin('UpdateLibrary(music)') 
开发者ID:bugatsinho,项目名称:bugatsinho.github.io,代码行数:25,代码来源:default.py

示例2: id3_parser

# 需要导入模块: from mutagen import mp3 [as 别名]
# 或者: from mutagen.mp3 import MP3 [as 别名]
def id3_parser(filename):
	"""
	The id3_parser function confirms the file type and sends it to
	be processed.
	:param filename: name of the file potentially containing exif
	metadata.
	:return: A dictionary from get_tags, containing the embedded
	EXIF metadata.
	"""

	# MP3 signatures
	signatures = ['494433']
	if processors.utility.check_header(
	filename, signatures, 3) == True:
		return get_tags(filename)
	else:
		print(('File signature does not match known '
		'MP3 signatures.'))
		raise TypeError(('File signature does not match ' 
		'MP3 object.')) 
开发者ID:PacktPublishing,项目名称:Learning-Python-for-Forensics-Second-Edition,代码行数:22,代码来源:id3_parser.py

示例3: main

# 需要导入模块: from mutagen import mp3 [as 别名]
# 或者: from mutagen.mp3 import MP3 [as 别名]
def main(filename):
    """
    The main function confirms the file type and sends it to
    be processed.
    :param filename: name of the file potentially containing exif
    metadata.
    :return: A dictionary from get_tags, containing the embedded
    EXIF metadata.
    """

    # MP3 signatures
    signatures = ['494433']
    if utility.check_header(filename, signatures, 3) is True:
        return get_tags(filename)
    else:
        raise TypeError 
开发者ID:PacktPublishing,项目名称:Learning-Python-for-Forensics-Second-Edition,代码行数:18,代码来源:id3.py

示例4: clear

# 需要导入模块: from mutagen import mp3 [as 别名]
# 或者: from mutagen.mp3 import MP3 [as 别名]
def clear():
    log('Clearing MP3 Streams Service')
    global COUNT
    global STARTED

    if xbmcgui.Window(10000).getProperty(RESOLVING) != RESOLVING:
        stopDownloaders()
        resetCache()
    else:
        log('Clearing cancelled due to RESOLVING property')

    COUNT   = 0
    STARTED = False 
开发者ID:bugatsinho,项目名称:bugatsinho.github.io,代码行数:15,代码来源:playerMP3.py

示例5: check

# 需要导入模块: from mutagen import mp3 [as 别名]
# 或者: from mutagen.mp3 import MP3 [as 别名]
def check():
    global COUNT
    if xbmc.Player().isPlaying():
        COUNT = 0
    else:
        COUNT += 1

        log('MP3 Service Checking Kodi is still trying to play %d' % COUNT)

        if COUNT > RETRIES:
            clear() 
开发者ID:bugatsinho,项目名称:bugatsinho.github.io,代码行数:13,代码来源:playerMP3.py

示例6: applyID3

# 需要导入模块: from mutagen import mp3 [as 别名]
# 或者: from mutagen.mp3 import MP3 [as 别名]
def applyID3(self):
         if ADDON.getSetting('keep_downloads')=='false':
             return 
         if not xbmcvfs.exists(self.filename):
             return

         if self.track < 1:
             return

         log('Applying ID3 tags to %s' % self.title)

         temp = self.filename.rsplit(os.sep, 1)[-1]
         temp = os.path.join(TEMP, temp)

         doCopy = self.filename != temp

         if doCopy:
             xbmcvfs.copy(self.filename, temp)

         #Remove track number from title
         title=self.title
         try: title=title[title.find('. ')+2:]
         except: title=title
		 
         audio = MP3(temp, ID3=EasyID3)
         audio['title']       = title
         audio['artist']      = self.artist
         audio['album']       = self.album
         audio['tracknumber'] = str(self.track)
         audio['date']        = ''
         audio['genre']       = ''
         audio.save(v1=2)
         log(audio.pprint())

         if doCopy:
             del audio 
             deleteFile(self.filename)
             xbmcvfs.copy(temp, self.filename)
             deleteFile(temp) 
开发者ID:bugatsinho,项目名称:bugatsinho.github.io,代码行数:41,代码来源:playerMP3.py

示例7: __str__

# 需要导入模块: from mutagen import mp3 [as 别名]
# 或者: from mutagen.mp3 import MP3 [as 别名]
def __str__(self):
        strings = ["-- Report for %s --" % self.name]
        if self.files == 0:
            return strings[0] + "\n" + "No MP3 files found.\n"

        good = self.files - len(self.errors)
        strings.append("Loaded %d/%d files (%d%%)" % (
            good, self.files, (float(good) / self.files) * 100))
        strings.append("%d files with unsynchronized frames." % self.unsync)
        strings.append("%d files without tags." % self.missings)

        strings.append("\nID3 Versions:")
        items = list(self.versions.items())
        items.sort()
        for v, i in items:
            strings.append("  %s\t%d" % (".".join(map(str, v)), i))

        if self.exceptions:
            strings.append("\nExceptions:")
            items = list(self.exceptions.items())
            items.sort()
            for Ex, i in items:
                strings.append("  %-20s\t%d" % (Ex.__name__, i))

        if self.errors:
            strings.append("\nERRORS:\n")
            for filename, Ex, value, trace in self.errors:
                strings.append("\nReading %s:" % filename)
                strings.append(
                    "".join(traceback.format_exception(Ex, value, trace)[1:]))
        else:
            strings.append("\nNo errors!")

        return("\n".join(strings)) 
开发者ID:bugatsinho,项目名称:bugatsinho.github.io,代码行数:36,代码来源:mutagen_pony.py

示例8: add_metadata_to_song

# 需要导入模块: from mutagen import mp3 [as 别名]
# 或者: from mutagen.mp3 import MP3 [as 别名]
def add_metadata_to_song(file_path, cover_path, song):
    # If no ID3 tags in mp3 file
    try:
        audio = MP3(file_path, ID3=ID3)
    except HeaderNotFoundError:
        print('Can\'t sync to MPEG frame, not an validate MP3 file!')
        return

    if audio.tags is None:
        print('No ID3 tag, trying to add one!')
        try:
            audio.add_tags()
            audio.save()
        except error as e:
            print('Error occur when add tags:', str(e))
            return

    # Modify ID3 tags
    id3 = ID3(file_path)
    # Remove old 'APIC' frame
    # Because two 'APIC' may exist together with the different description
    # For more information visit: http://mutagen.readthedocs.io/en/latest/user/id3.html
    if id3.getall('APIC'):
        id3.delall('APIC')
    # add album cover
    id3.add(
        APIC(
            encoding=0,         # 3 is for UTF8, but here we use 0 (LATIN1) for 163, orz~~~
            mime='image/jpeg',  # image/jpeg or image/png
            type=3,             # 3 is for the cover(front) image
            data=open(cover_path, 'rb').read()
        )
    )
    # add artist name
    id3.add(
        TPE1(
            encoding=3,
            text=song['artists'][0]['name']
        )
    )
    # add song name
    id3.add(
        TIT2(
            encoding=3,
            text=song['name']
        )
    )
    # add album name
    id3.add(
        TALB(
            encoding=3,
            text=song['album']['name']
        )
    )
    id3.save(v2_version=3) 
开发者ID:codezjx,项目名称:netease-cloud-music-dl,代码行数:57,代码来源:file_util.py

示例9: decrypt

# 需要导入模块: from mutagen import mp3 [as 别名]
# 或者: from mutagen.mp3 import MP3 [as 别名]
def decrypt(self, musicId, name):
        def _decrypt(cachePath):
            with open(cachePath, 'rb') as f:
                btay = bytearray(f.read())
            for i, j in enumerate(btay):
                btay[i] = j ^ 0xa3
            return btay
        cachePath = os.path.join(self.path, name)
        idpath = os.path.join(MSCDIR, musicId + '.mp3')
        info = self.getInfoFromWeb(musicId)
        path = self.getPath(info, musicId)
        if not os.path.exists(path):
            with open(path, 'wb') as f:
                f.write(bytes(_decrypt(cachePath)))

        '''  get info from index file
        if not os.path.exists(idpath):
            with open(idpath, 'wb') as f:
                f.write(bytes(_decrypt(cachePath)))
        try:
            info = dict(MP3(idpath, ID3=EasyID3))
        except:
            info = {}
        if info != {}:
            path = self.getPath(info, musicId)
            if os.path.exists(path):
                os.remove(idpath)
            else:
                os.rename(idpath, path)
        else:
            os.remove(idpath)
        '''
        return info, path 
开发者ID:mbinary,项目名称:netease-music-cracker,代码行数:35,代码来源:decrypt.py

示例10: initialize

# 需要导入模块: from mutagen import mp3 [as 别名]
# 或者: from mutagen.mp3 import MP3 [as 别名]
def initialize(file):
        audio = mutagen.File(file)
        if (isinstance(audio, MP4)):
            return mp4Editor(file)
        if (isinstance(audio, MP3)):
            return mp3Editor(file) 
开发者ID:LXG-Shadow,项目名称:BilibiliTools,代码行数:8,代码来源:infoEditor.py

示例11: __init__

# 需要导入模块: from mutagen import mp3 [as 别名]
# 或者: from mutagen.mp3 import MP3 [as 别名]
def __init__(self, file):
        super().__init__(file)
        self.audio = MP3(file, ID3=EasyID3)  # type: MP3
        self.titleTag = "title"
        self.artistTag = "artist" 
开发者ID:LXG-Shadow,项目名称:BilibiliTools,代码行数:7,代码来源:infoEditor.py

示例12: reload

# 需要导入模块: from mutagen import mp3 [as 别名]
# 或者: from mutagen.mp3 import MP3 [as 别名]
def reload(self):
        self.audio = MP3(self.file, ID3=EasyID3) 
开发者ID:LXG-Shadow,项目名称:BilibiliTools,代码行数:4,代码来源:infoEditor.py

示例13: fill

# 需要导入模块: from mutagen import mp3 [as 别名]
# 或者: from mutagen.mp3 import MP3 [as 别名]
def fill(self, func, limit=0):
        """
        Download the song, and fill in its length field.

        Arguments:
        func: Irrelevant.

        Keyword arguments:
        limit=0: Irrelevant.
        """
        # Can't have '/' in filenames so replace with them with something
        # that will (hopefully) never occur naturally.
        dl_path = join(
            common.DATA_DIR, 'songs', '%s.mp3' % str(self).replace('/', '---')
        )
        dl = False
        if not isfile(dl_path):
            common.w.outbar_msg('Downloading %s...' % str(self))
            with open(dl_path, 'wb') as f:
                f.write(common.client.mm.download_song(self['id'])[1])
            self['full'] = True
            dl = True
        try:
            self['time'] = LibrarySong.time_from_s(MP3(dl_path).info.length)
        except:  # Todo: look into more specific mutagen errors.
            remove(dl_path)
            if not dl:  # File might be corrupt, so re-download it.
                self.fill(None)
            else:  # Otherwise we're out of luck.
                common.w.outbar_msg('Song could not be downloaded.')


# Music object mapping:
# cls: Class name of each type.
# hits: Key in mc.search() results.
# rslt_key: Key in an individual entry from mc.search()
# lookup: method to retrieve object information 
开发者ID:christopher-dG,项目名称:gpymusic,代码行数:39,代码来源:music_objects.py

示例14: load_labeled_intervals

# 需要导入模块: from mutagen import mp3 [as 别名]
# 或者: from mutagen.mp3 import MP3 [as 别名]
def load_labeled_intervals(filename, delimiter=r'\s+'):
    """
    overwrites https://github.com/craffel/mir_eval/blob/master/mir_eval/io.py#L208
    ends of intervals are not used later in evaluation, vut are needed for sanity check
    """
    # Use our universal function to load in the events
    
    starts, ends, labels = load_delimited_variants(filename, delimiter)
    
    if ends is None:  # add ends

        filename_base = remove_extension(filename)
        if "_word_corrected" in filename_base:
            filename_base = filename_base.replace("_word_corrected", "")
        filename_wav = filename_base + '.wav'
        filename_mp3 = filename_base + '.mp3'
        if not os.path.isfile(filename_wav) and not os.path.isfile(filename_mp3):
            raise IOError("not found file {}".format(filename_base))
            # dir = ''
            # while not os.path.isfile(filename_wav):
            #     dir = raw_input('cannot find {} \n Please enter folder where the wav file is:'.format(filename_wav))
            #     filename_wav = os.path.join(dir, os.path.basename(filename_wav))
        if os.path.isfile(filename_wav):
            duration = get_duration_audio(filename_wav)  # generate end timestamps from following start timestamps
        elif os.path.isfile(filename_mp3):
            # audio_mp3 = mad.MadFile(filename_mp3)
            audio_mp3 = MP3(filename_mp3)
            duration = audio_mp3.info.length
            # duration = audio_mp3.total_time()
            # print(duration)
            # raise ValueError
#         duration = starts[-1] + 1 # fake last word to be 1 sec long
        ends = starts[1:]
        ends = np.append(ends, duration)
    
    starts, ends, labels = remove_dot_tokens(starts, ends, labels)  # special words  '.' are discarded
     
    # Stack into an interval matrix
    intervals = np.array([starts, ends]).T
    # Validate them, but throw a warning in place of an error
    try:
        util.validate_intervals(intervals)
    except ValueError as error:
        warnings.warn(error.args[0])

    return intervals, labels 
开发者ID:ronggong,项目名称:MIREX-2018-Automatic-Lyrics-to-Audio-Alignment,代码行数:48,代码来源:Utilz.py

示例15: get_tags

# 需要导入模块: from mutagen import mp3 [as 别名]
# 或者: from mutagen.mp3 import MP3 [as 别名]
def get_tags(filename):
	"""
	The get_tags function extracts the ID3 metadata from the data
	object.
	:param filename: the path and name to the data object.
	:return: tags and headers, tags is a dictionary containing ID3
	metadata and headers are the order of keys for the CSV output.
	"""

	# Set up CSV headers
	header = ['Path', 'Name', 'Size', 'Filesystem CTime',
	'Filesystem MTime', 'Title', 'Subtitle', 'Artist', 'Album',
	'Album/Artist', 'Length (Sec)', 'Year', 'Category',
	'Track Number', 'Comments', 'Publisher', 'Bitrate',
	'Sample Rate', 'Encoding', 'Channels', 'Audio Layer']
	tags = {}
	tags['Path'] = filename
	tags['Name'] = os.path.basename(filename)
	tags['Size'] = processors.utility.convert_size(
	os.path.getsize(filename))
	tags['Filesystem CTime'] = strftime('%m/%d/%Y %H:%M:%S',
	gmtime(os.path.getctime(filename)))
	tags['Filesystem MTime'] = strftime('%m/%d/%Y %H:%M:%S',
	gmtime(os.path.getmtime(filename)))

	# MP3 Specific metadata
	audio = mp3.MP3(filename)
	if 'TENC' in audio.keys():
		tags['Encoding'] = audio['TENC'][0]
	tags['Bitrate'] = audio.info.bitrate
	tags['Channels'] = audio.info.channels
	tags['Audio Layer'] = audio.info.layer
	tags['Length (Sec)'] = audio.info.length
	tags['Sample Rate'] = audio.info.sample_rate

	# ID3 embedded metadata tags
	id = id3.ID3(filename)
	if 'TPE1' in id.keys():
		tags['Artist'] = id['TPE1'][0]
	if 'TRCK' in id.keys():
		tags['Track Number'] = id['TRCK'][0]
	if 'TIT3' in id.keys():
		tags['Subtitle'] = id['TIT3'][0]
	if 'COMM::eng' in id.keys():
		tags['Comments'] = id['COMM::eng'][0]
	if 'TDRC' in id.keys():
		tags['Year'] = id['TDRC'][0]
	if 'TALB' in id.keys():
		tags['Album'] = id['TALB'][0]
	if 'TIT2' in id.keys():
		tags['Title'] = id['TIT2'][0]
	if 'TCON' in id.keys():
		tags['Category'] = id['TCON'][0]
	if 'TPE2' in id.keys():
		tags['Album/Artist'] = id['TPE2'][0]
	if 'TPUB' in id.keys():
		tags['Publisher'] = id['TPUB'][0]

	return tags, header 
开发者ID:PacktPublishing,项目名称:Learning-Python-for-Forensics-Second-Edition,代码行数:61,代码来源:id3_parser.py


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