本文整理汇总了Python中mutagen.mp4.MP4属性的典型用法代码示例。如果您正苦于以下问题:Python mp4.MP4属性的具体用法?Python mp4.MP4怎么用?Python mp4.MP4使用的例子?那么, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类mutagen.mp4
的用法示例。
在下文中一共展示了mp4.MP4属性的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: compare
# 需要导入模块: from mutagen import mp4 [as 别名]
# 或者: from mutagen.mp4 import MP4 [as 别名]
def compare(music_file, metadata):
"""Check if the input music file title matches the expected title."""
already_tagged = False
try:
if music_file.endswith('.mp3'):
audiofile = EasyID3(music_file)
# fetch track title metadata
already_tagged = audiofile['title'][0] == metadata['name']
elif music_file.endswith('.m4a'):
tags = {'title': '\xa9nam'}
audiofile = MP4(music_file)
# fetch track title metadata
already_tagged = audiofile[tags['title']] == metadata['name']
except (KeyError, TypeError):
pass
return already_tagged
示例2: insert_mp4_artwork
# 需要导入模块: from mutagen import mp4 [as 别名]
# 或者: from mutagen.mp4 import MP4 [as 别名]
def insert_mp4_artwork(mp4_path, artwork_path):
from mutagen.mp4 import MP4, MP4Cover
mp4 = MP4(mp4_path)
f = open(artwork_path, 'rb')
artwork = f.read()
f.close()
mp4['covr'] = [MP4Cover(artwork, imageformat=MP4Cover.FORMAT_JPEG)]
mp4.save()
示例3: write_meta
# 需要导入模块: from mutagen import mp4 [as 别名]
# 或者: from mutagen.mp4 import MP4 [as 别名]
def write_meta(self, player_id, path):
""" Try to write metadata to the file. """
try:
if path.endswith('.mp4'):
from mutagen.mp4 import MP4
meta = self.meta(player_id)
fp = MP4(path)
fp['tvsh'] = meta.get('serie', {}).get('serie_titel', '')
fp['desc'] = (meta.get('aflevering_titel', '') or
meta.get('titel', None) or
meta.get('title', ''))
fp.save()
elif path.endswith('.mp3'):
from mutagen.mp3 import MP3
meta = self.meta(player_id)
fp = MP3(path)
# TODO
fp.save()
except ImportError:
print('\nmutagen module niet gevonden; metadata niet ingesteld.',
file=sys.stderr)
return
示例4: tags_from_song_model_to_m4a
# 需要导入模块: from mutagen import mp4 [as 别名]
# 或者: from mutagen.mp4 import MP4 [as 别名]
def tags_from_song_model_to_m4a(song, file_path):
"""
Read all the new model attributes and save them according to the MP4 tags
of the m4a stored file
"""
# Creating an MP4 tag if not present or read it if present
try:
tags = MP4(file_path).tags
except ValueError:
tags = MP4Tags()
save_song_attrs_to_mp4tags(tags, song)
tags.save(file_path)
###############################################################################
# AIFF #
###############################################################################
示例5: poll
# 需要导入模块: from mutagen import mp4 [as 别名]
# 或者: from mutagen.mp4 import MP4 [as 别名]
def poll(self, context):
scene = context.scene
try:
from PIL import Image
from mutagen.mp4 import MP4, MP4Cover
from mutagen.mp3 import MP3
except ImportError:
return False
if os.path.isfile(scene.bbz_config) and scene.bbz_config.endswith('.csv'):
return True
else:
return False
示例6: __get_m4a_tag
# 需要导入模块: from mutagen import mp4 [as 别名]
# 或者: from mutagen.mp4 import MP4 [as 别名]
def __get_m4a_tag(self, file_path):
music_tag = {}
try:
audio = MP4(file_path)
music_tag[music.TRACK_TITLE] = "".join(audio.tags.get(self.MP4_TRACK_TITLE)) \
if audio.tags.get(self.MP4_TRACK_TITLE) is not None else ''
music_tag[music.ALBUM] = "".join(audio.tags.get(self.MP4_ALBUM)) \
if audio.tags.get(self.MP4_ALBUM) is not None else ''
music_tag[music.ALBUM_ARTIST] = "".join(audio.tags.get(self.MP4_ALBUM_ARTIST)) \
if audio.tags.get(self.MP4_ALBUM_ARTIST) is not None else ''
music_tag[music.ARTIST] = "".join(audio.tags.get(self.MP4_ARTIST)) \
if audio.tags.get(self.MP4_ARTIST) is not None else ''
music_tag[music.HAS_COVER] = audio.tags.get(self.MP4_COVER) != [0]
music_tag[music.FILE_TYPE] = 'm4a'
except FileNotFoundError:
print("File not found: " + file_path)
except mutagen.mp4.MP4StreamInfoError:
print("It may be not a mp4 file: " + file_path)
except mutagen.mp4.MutagenError:
print("Some Err get!!!")
# print(music_tag)
return music_tag
示例7: m4a_tags_to_song_model
# 需要导入模块: from mutagen import mp4 [as 别名]
# 或者: from mutagen.mp4 import MP4 [as 别名]
def m4a_tags_to_song_model(file_name, file_path, song):
"""
Read all the tags from a m4a file an store them according to the
song model attributes
"""
try:
audio_file = MP4(file_path)
if audio_file:
read_and_store_mp4_tags(audio_file, file_name, song)
# Get the song length
song.duration = timedelta(seconds=int(audio_file.info.length))
except ValueError:
pass
示例8: __get_media_type
# 需要导入模块: from mutagen import mp4 [as 别名]
# 或者: from mutagen.mp4 import MP4 [as 别名]
def __get_media_type(path):
"""
Tests a given file for the media type.
:param path: Path to the file
:return: Media type as string
"""
try:
fileobj = open(path, "rb")
header = fileobj.read(128)
except IOError as e:
log.warning(e)
return ""
path = path.lower()
# MP4
if b"ftyp" in header or b"mp4" in header:
return "mp4"
# OGG
elif header.startswith(b"OggS") or b"\x01vorbis" in header:
return "ogg"
# FLAC
elif header.startswith(b"fLaC") or path.endswith(".flac"):
return "flac"
# MP3
elif header.startswith(b"ID3") or path.endswith(".mp3") or path.endswith(".mp2") or path.endswith(".mpg") or path.endswith(".mpeg"):
return "mp3"
else:
return ""
示例9: __get_mp4_cover
# 需要导入模块: from mutagen import mp4 [as 别名]
# 或者: from mutagen.mp4 import MP4 [as 别名]
def __get_mp4_cover(track):
"""
Get the cover of an MP4 file.
:param track: Track object
"""
cover = None
try:
cover = track.mutagen.tags["covr"][0]
except Exception as e:
log.debug("Could not load cover for file " + track.path)
log.debug(e)
return cover
示例10: add_cover
# 需要导入模块: from mutagen import mp4 [as 别名]
# 或者: from mutagen.mp4 import MP4 [as 别名]
def add_cover(filename, video_id):
raw_image = open_page('http://img.youtube.com/vi/%s/0.jpg' % video_id)
audio = MP4(filename)
cover = MP4Cover(raw_image)
audio['covr'] = [cover]
audio.save()
示例11: embed_m4a
# 需要导入模块: from mutagen import mp4 [as 别名]
# 或者: from mutagen.mp4 import MP4 [as 别名]
def embed_m4a(music_file, meta_tags):
""" Embed metadata to M4A files. """
# Apple has specific tags - see mutagen docs -
# http://mutagen.readthedocs.io/en/latest/api/mp4.html
tags = {'album': '\xa9alb',
'artist': '\xa9ART',
'date': '\xa9day',
'title': '\xa9nam',
'originaldate': 'purd',
'comment': '\xa9cmt',
'group': '\xa9grp',
'writer': '\xa9wrt',
'genre': '\xa9gen',
'tracknumber': 'trkn',
'albumartist': 'aART',
'disknumber': 'disk',
'cpil': 'cpil',
'albumart': 'covr',
'copyright': 'cprt',
'tempo': 'tmpo'}
audiofile = MP4(music_file)
audiofile[tags['artist']] = meta_tags['artists'][0]['name']
audiofile[tags['albumartist']] = meta_tags['artists'][0]['name']
audiofile[tags['album']] = meta_tags['album']['name']
audiofile[tags['title']] = meta_tags['name']
audiofile[tags['tracknumber']] = [(meta_tags['track_number'],
meta_tags['total_tracks'])]
audiofile[tags['disknumber']] = [(meta_tags['disc_number'], 0)]
audiofile[tags['date']] = meta_tags['release_date']
audiofile[tags['originaldate']] = meta_tags['release_date']
if meta_tags['genre']:
audiofile[tags['genre']] = meta_tags['genre']
if meta_tags['copyright']:
audiofile[tags['copyright']] = meta_tags['copyright']
try:
albumart = urllib.request.urlopen(meta_tags['album']['images'][0]['url'])
audiofile[tags['albumart']] = [MP4Cover(
albumart.read(), imageformat=MP4Cover.FORMAT_JPEG)]
albumart.close()
except IndexError:
pass
audiofile.save()
return True
示例12: get_mp4_metadata
# 需要导入模块: from mutagen import mp4 [as 别名]
# 或者: from mutagen.mp4 import MP4 [as 别名]
def get_mp4_metadata(filepath, covers_root):
meta_raw = MP4(filepath)
data_bin = pydub.AudioSegment.from_file(filepath)
meta = {
'rawhash': hashlib.md5(data_bin.raw_data).hexdigest(),
'title': meta_raw.get('\xa9nam'),
'album': meta_raw.get('\xa9alb'),
'artist': meta_raw.get('\xa9ART'),
'year': meta_raw.get('\xa9day'),
'grouping': meta_raw.get('\xa9grp'),
'genre': meta_raw.get('\xa9gen'),
'track': meta_raw.get('trkn'), # n/t
'disk': meta_raw.get('disk'), # n/t
'filepath': filepath[len(media_root):],
'length': meta_raw.info.length,
'bitrate': meta_raw.info.bitrate,
'codec': meta_raw.info.codec,
}
# Clear outside []
for key in iter(meta):
if isinstance(meta[key], list):
meta[key] = meta[key][0]
# Normalize data
# meta['country'] = get_country(meta)
if meta['codec'] != 'alac':
meta['codec'] = 'aac'
if len(meta['year']) > 4:
meta['year'] = meta['year'][:4]
if meta['track']:
meta['track_n'] = meta['track'][0]
meta['track_t'] = meta['track'][1]
if meta['disk']:
meta['disk_n'] = meta['disk'][0]
meta['disk_t'] = meta['disk'][1]
meta.pop('track', None)
meta.pop('disk', None)
cover_raw = meta_raw.get('covr')
if cover_raw:
cover_bin = MP4Cover(cover_raw[0])
meta['coverhash'] = hashlib.md5(cover_bin).hexdigest()
coverpath = os.path.join(covers_root, meta['coverhash']) + '.jpg'
if not os.path.exists(coverpath):
with open(coverpath, "wb") as fp:
fp.write(cover_bin)
return meta
示例13: process_video
# 需要导入模块: from mutagen import mp4 [as 别名]
# 或者: from mutagen.mp4 import MP4 [as 别名]
def process_video(filename: str, user: str, date=None, caption=None,
tags=None, code=None):
"""Use Mutagen to embed metadata to a video file
filename: This can be a cwd file or a full PATH
Example: 'image.jpg' or '/home/you/Pictures/image.jpg'
user: Username
Example: 'sportscenter'
date: Formatted as YYYY:MM:DD HH:MM:SS
Example: '2016:12:25 06:03:49'
caption: Caption
Example: 'This is a caption'
tags: List of tags.
Example: ['single tag'] or ['multiple', 'tags']
code: Add an Instagram shortcode to the title
Example: 'BapbIcAFsCL'
"""
title = user
if code:
title += ' - {}'.format(code)
try:
video = MP4(filename)
except MP4StreamInfoError:
print('\n[!] Can\'t write tags for {}'.format(filename))
print('[!] It probably didn\'t download correctly\n')
return
video.delete() # existing metadata
video['\xa9nam'] = title
if caption:
video['desc'] = caption
video['ldes'] = caption # Long
video['\xa9cmt'] = caption[:255] # Comment
if date and correct_date_format(date):
video['purd'] = date # Purchase Date
video['\xa9day'] = date.split(':')[0] # Year
if tags and isinstance(tags, list):
video['\xa9gen'] = ','.join(tags) # Genres
video['keyw'] = ','.join(tags) # Podcast Keywords
video['\xa9ART'] = user # Arist
video['cprt'] = user # Copyright
video['----:com.apple.iTunes:iTunMOVI'] = xml_tags(user) # Actor
video.save()