Exemple #1
0
def fix_tags(abs, ext, f_meta):
    """
	:param abs: Path of the file we're tagging
	:param ext: Extension of the file we're tagging
	:param f_meta: Dict containing the metadata of the track we're tagging.
	"""
    if ext == "mp3":
        try:
            audio = id3.ID3(abs)
        except ID3NoHeaderError:
            audio = id3.ID3()
        audio['TRCK'] = id3.TRCK(text=str(audio['TRCK']) + "/" +
                                 str(f_meta['track_total']))
        audio['TPOS'] = id3.TPOS(text=str(audio['TPOS']) + "/" +
                                 str(f_meta['disc_total']))
        audio['TDRC'] = id3.TPOS(text=f_meta['release_date'])
        audio['TPUB'] = id3.TPOS(text=f_meta['planning'])
        audio['TPE1'] = id3.TPE1(text=f_meta['track_artist'])
        audio['TPE2'] = id3.TPE2(text=f_meta['album_artist'])
        audio.save(abs, "v2_version=3")
    else:
        audio = FLAC(abs)
        audio['TRACKTOTAL'] = str(f_meta['track_total'])
        audio['DISCTOTAL'] = str(f_meta['disc_total'])
        audio['DATE'] = f_meta['release_date']
        audio['LABEL'] = f_meta['planning']
        audio['ARTIST'] = f_meta['track_artist']
        audio['ALBUMARTIST'] = f_meta['album_artist']
        audio.save()
Exemple #2
0
 def loadFile(self, _filePath):
     self.tags = None
     self.info = None
     self.filePath = _filePath
     self.isCorrect = False
     self.isSave = False
     self.isNeedUpdate = False
     try:
         self.tags = id3.ID3(
             uni.trEncode(self.filePath, fu.fileSystemEncoding))
         self.info = mp3.MP3(
             uni.trEncode(self.filePath, fu.fileSystemEncoding)).info
     except id3.error:
         self.isNeedUpdate = True
         self.isSave = True
         self.tags = id3.ID3()
         self.tags.add(id3.TPE1(encoding=3, text=""))
         self.tags.save(uni.trEncode(self.filePath, fu.fileSystemEncoding))
         self.tags = id3.ID3(
             uni.trEncode(self.filePath, fu.fileSystemEncoding))
         self.info = mp3.MP3(
             uni.trEncode(self.filePath, fu.fileSystemEncoding)).info
     except:
         self.tags = id3.ID3(self.filePath)
         self.info = mp3.MP3(self.filePath).info
     if self.tags.version is not (2, 4, 0):
         self.isNeedUpdate = True
         self.isSave = True
Exemple #3
0
def add_mp3_tags(filename, metadata):
    metadata = metadata.copy()
    try:
        audio = id3.ID3(filename)
    except ID3NoHeaderError:
        audio = id3.ID3()
    # ID3 is weird about the track number and total so we have to set that manually
    audio["TRCK"] = id3.TRCK(
        encoding=3,
        text=f"{metadata.pop('TRACKNUMBER')}/{metadata.pop('TRACKTOTAL')}")
    legend = {
        "ALBUM": id3.TALB,
        "ALBUMARTIST": id3.TPE2,
        "ARTIST": id3.TPE1,
        "COMMENT": id3.COMM,
        "COMPOSER": id3.TCOM,
        "COPYRIGHT": id3.TCOP,
        "GENRE": id3.TCON,
        "ORGANIZATION": id3.TPUB,
        "TITLE": id3.TIT2,
        "ISRC": id3.TSRC,
        "DATE": id3.TYER
    }
    for tag, value in metadata.items():
        if value:
            id3tag = legend[tag]
            audio[id3tag.__name__] = id3tag(encoding=3, text=value)
    audio.save(filename, 'v2_version=3')
Exemple #4
0
def write_tags(f, meta, cov):
    if f.endswith('.mp3'):
        try:
            audio = id3.ID3(f)
        except ID3NoHeaderError:
            audio = id3.ID3()
        audio['TRCK'] = id3.TRCK(encoding=3,
                                 text=str(meta['TRACK']) + "/" +
                                 str(meta['TRACKTOTAL']))
        legend = {
            "ALBUM": id3.TALB,
            "ALBUMARTIST": id3.TPE2,
            "ARTIST": id3.TPE1,
            "COPYRIGHT": id3.TCOP,
            "TITLE": id3.TIT2,
            "YEAR": id3.TYER
        }
        for tag, value in meta.items():
            if not tag in ['UPC', 'TRACK', 'TRACKTOTAL']:
                id3tag = legend[tag]
                audio[id3tag.__name__] = id3tag(encoding=3, text=value)
        with open(cov, 'rb') as cov_obj:
            audio.add(id3.APIC(3, 'image/jpeg', 3, '', cov_obj.read()))
        audio.save(f, 'v2_version=3')
    else:
        audio = FLAC(f)
        for tag, value in meta.items():
            audio[tag] = str(value)
            image = Picture()
        image.type = 3
        image.mime = "image/jpeg"
        with open(cov, 'rb') as cov_obj:
            image.data = cov_obj.read()
            audio.add_picture(image)
        audio.save()
Exemple #5
0
        def set_id3_tags_raw(audio, audio_file):
            try:
                id3_dict = id3.ID3(audio_file)
            except id3.ID3NoHeaderError:
                id3_dict = id3.ID3()

            def embed_image(data):
                id3_dict.add(
                    id3.APIC(encoding=3,
                             mime='image/jpeg',
                             type=3,
                             desc='Front Cover',
                             data=data))

            save_cover_image(embed_image)

            if album is not None:
                id3_dict.add(
                    id3.TALB(text=[tag_to_ascii(track.album.name, album)],
                             encoding=3))
            id3_dict.add(
                id3.TIT2(text=[tag_to_ascii(track.name, title)], encoding=3))
            id3_dict.add(
                id3.TPE1(text=[tag_to_ascii(artists, artists_ascii)],
                         encoding=3))
            if album_artist is not None:
                id3_dict.add(
                    id3.TPE2(text=[
                        tag_to_ascii(track.album.artist.name, album_artist)
                    ],
                             encoding=3))
            id3_dict.add(id3.TDRC(text=[str(track.album.year)], encoding=3))
            id3_dict.add(
                id3.TPOS(text=[idx_of_total_str(track.disc, num_discs)],
                         encoding=3))
            id3_dict.add(
                id3.TRCK(text=[idx_of_total_str(track.index, num_tracks)],
                         encoding=3))
            if args.comment is not None:
                id3_dict.add(
                    id3.COMM(text=[tag_to_ascii(comment, comment_ascii)],
                             encoding=3))
            if args.grouping is not None:
                audio.tags.add(
                    id3.TIT1(text=[tag_to_ascii(grouping, grouping_ascii)],
                             encoding=3))
            if genres is not None and genres:
                tcon_tag = id3.TCON(encoding=3)
                tcon_tag.genres = genres if args.ascii_path_only \
                    else genres_ascii
                id3_dict.add(tcon_tag)

            if args.id3_v23:
                id3_dict.update_to_v23()
                id3_dict.save(audio_file, v2_version=3, v23_sep='/')
                id3_dict.version = (2, 3, 0)
            else:
                id3_dict.save(audio_file)
            audio.tags = id3_dict
def write_tags(f, meta, tag_cfg, cov, ext, embed_cov):
    if ext == ".flac":
        audio = FLAC(f)
        for k, v in meta.items():
            if tag_cfg[k]:
                audio[k] = str(v)
        if embed_cov and cov:
            with open(cov, 'rb') as cov_obj:
                image = Picture()
                image.type = 3
                image.mime = "image/jpeg"
                image.data = cov_obj.read()
                audio.add_picture(image)
        audio.save()
    elif ext == ".mp3":
        try:
            audio = id3.ID3(f)
        except ID3NoHeaderError:
            audio = id3.ID3()
        if tag_cfg['TRACKNUMBER'] and tag_cfg['TRACKTOTAL']:
            audio['TRCK'] = id3.TRCK(encoding=3,
                                     text=str(meta['TRACKNUMBER']) + "/" +
                                     str(meta['TRACKTOTAL']))
        elif tag_cfg['TRACKNUMBER']:
            audio['TRCK'] = id3.TRCK(encoding=3, text=str(meta['TRACKNUMBER']))
        if tag_cfg['DISCNUMBER']:
            audio['TPOS'] = id3.TPOS(encoding=3,
                                     text=str(meta['DISCNUMBER']) + "/" +
                                     str(meta['DISCTOTAL']))
        legend = {
            "ALBUM": id3.TALB,
            "ALBUMARTIST": id3.TPE2,
            "ARTIST": id3.TPE1,
            "COMMENT": id3.COMM,
            "COMPOSER": id3.TCOM,
            "COPYRIGHT": id3.TCOP,
            "DATE": id3.TDAT,
            "GENRE": id3.TCON,
            "ISRC": id3.TSRC,
            "LABEL": id3.TPUB,
            "PERFORMER": id3.TOPE,
            "TITLE": id3.TIT2,
            # Not working.
            "URL": id3.WXXX,
            "YEAR": id3.TYER
        }
        for k, v in meta.items():
            try:
                if tag_cfg[k]:
                    id3tag = legend[k]
                    audio[id3tag.__name__] = id3tag(encoding=3, text=v)
            except KeyError:
                pass
        if embed_cov and cov:
            with open(cov, 'rb') as cov_obj:
                audio.add(id3.APIC(3, 'image/jpeg', 3, '', cov_obj.read()))
        audio.save(f, 'v2_version=3')
Exemple #7
0
def write_tags(pre_abs, meta, fmt, cov_abs):
    if fmt == "FLAC":
        audio = FLAC(pre_abs)
        del meta['track_padded']
        for k, v in meta.items():
            if v:
                audio[k] = str(v)
        if cov_abs:
            with open(cov_abs, "rb") as f:
                image = Picture()
                image.type = 3
                image.mime = "image/jpeg"
                image.data = f.read()
                audio.add_picture(image)
    elif fmt == "MP3":
        try:
            audio = id3.ID3(pre_abs)
        except ID3NoHeaderError:
            audio = id3.ID3()
        audio['TRCK'] = id3.TRCK(encoding=3,
                                 text="{}/{}".format(meta['track'],
                                                     meta['tracktotal']))
        legend = {
            "album": id3.TALB,
            "albumartist": id3.TPE2,
            "artist": id3.TPE1,
            #"comment": id3.COMM,
            "copyright": id3.TCOP,
            "isrc": id3.TSRC,
            "label": id3.TPUB,
            "title": id3.TIT2,
            "year": id3.TYER
        }
        for k, v in meta.items():
            id3tag = legend.get(k)
            if v and id3tag:
                audio[id3tag.__name__] = id3tag(encoding=3, text=v)
        if cov_abs:
            with open(cov_abs, "rb") as cov_obj:
                audio.add(id3.APIC(3, "image/jpeg", 3, None, cov_obj.read()))
    else:
        audio = MP4(pre_abs)
        audio['\xa9nam'] = meta['title']
        audio['\xa9alb'] = meta['album']
        audio['aART'] = meta['albumartist']
        audio['\xa9ART'] = meta['artist']
        audio['trkn'] = [(meta['track'], meta['tracktotal'])]
        audio['\xa9day'] = meta['year']
        audio['cprt'] = meta['copyright']
        if cov_abs:
            with open(cov_abs, "rb") as f:
                audio['covr'] = [
                    MP4Cover(f.read(), imageformat=MP4Cover.FORMAT_JPEG)
                ]
    audio.save(pre_abs)
Exemple #8
0
def tag(album, track, file_path, cover_path):
    lyrics = get_lyrics(track['lyrics_tp'], track['track_id'])
    meta = utils.organize_meta(album=album, track=track, lyrics=lyrics)
    if str(file_path).endswith('.flac'):
        if cover_path:
            f_file = FLAC(file_path)
            f_image = Picture()
            f_image.type = 3
            f_image.desc = 'Front Cover'
            with open(cover_path, 'rb') as f:
                f_image.data = f.read()
            f_file.add_picture(f_image)
            f_file.save()
        f = FLAC(file_path)
        logger_bugs.debug("Writing tags to {}".format(
            os.path.basename(file_path)))
        for k, v in meta.items():
            f[k] = str(v)
        f.save()
    if str(file_path).endswith('.mp3'):
        legend = {
            "ALBUM": id3.TALB,
            "ALBUMARTIST": id3.TPE2,
            "ARTIST": id3.TPE1,
            "TRACKNUMBER": id3.TRCK,
            "DISCNUMBER": id3.TPOS,
            "COMMENT": id3.COMM,
            "COMPOSER": id3.TCOM,
            "COPYRIGHT": id3.TCOP,
            "DATE": id3.TDRC,
            "GENRE": id3.TCON,
            "ISRC": id3.TSRC,
            "LABEL": id3.TPUB,
            "PERFORMER": id3.TOPE,
            "TITLE": id3.TIT2,
            "LYRICS": id3.USLT
        }
        try:
            audio = id3.ID3(file_path)
        except ID3NoHeaderError:
            audio = id3.ID3()
        logger_bugs.debug("Writing tags to {}".format(
            os.path.basename(file_path)))
        for k, v in meta.items():
            try:
                id3tag = legend[k]
                audio[id3tag.__name__] = id3tag(encoding=3, text=v)
            except KeyError:
                pass
        if cover_path:
            with open(cover_path, 'rb') as cov_obj:
                audio.add(id3.APIC(3, 'image/jpg', 3, '', cov_obj.read()))
            audio.save(file_path, 'v2_version=3')
Exemple #9
0
 def song_info_insert(filepath, song_name, artist_name, album_name):
     with open('cover.jpg', 'rb') as f:
         pic_data = f.read()
     info = {
         'picData': pic_data,
         'title': song_name,
         'artist': artist_name,
         'album': album_name
     }
     filepath += '.mp3'
     try:
         song_file = id3.ID3(filepath)
         song_file['APIC'] = id3.APIC(  # 插入封面
             encoding=3,
             mime='image/jpeg',
             type=3,
             desc=u'Cover',
             data=info['picData'])
         song_file['TIT2'] = id3.TIT2(  # 插入歌名
             encoding=3, text=info['title'])
         song_file['TPE1'] = id3.TPE1(  # 插入歌手
             encoding=3, text=info['artist'])
         song_file['TALB'] = id3.TALB(  # 插入专辑名
             encoding=3, text=info['album'])
         song_file.save()
     except Exception as error:
         print('无法写入歌曲信息')
         print(f'报错:{error}')
     finally:
         os.remove('cover.jpg')
def __main() -> None:
    args = __configure_args()

    wave_file = WaveFile(args.input)
    if args.include_chapters:
        chapters_data: List[Tuple[int, int, str]] = wave_file.read_chapters()

    audio_data: BytesIO = encode(wave_file)
    wave_file.close()

    tags = id3.ID3()

    if args.podcast_name:
        add_podcast_name(tags, args.podcast_name)

    if args.episode_number:
        add_episode_number(tags, args.episode_number)

    if args.episode_title:
        add_episode_title(tags, args.episode_title)

    if args.include_chapters:
        add_chapters(tags, chapters_data)

    tags.save(audio_data)

    with open(args.output, "wb") as file:
        file.write(audio_data.getvalue())
Exemple #11
0
async def tag(path, metadata, session=None):
    audio = mp3.MP3(path)
    audio.tags = id3.ID3()

    for maker in tagmaker.tag_makers:
        tag = maker(metadata)
        if tag:
            audio.tags.add(tag)

    if keys.IMAGE_LINK in metadata:
        url = metadata.get(keys.IMAGE_LINK)
        if session:
            mime, _ = mimetypes.guess_type(url)
            async with session.get(url) as response:
                data = await response.read()
                audio.tags.add(
                    id3.APIC(encoding=id3.Encoding.UTF8,
                             mime=mime,
                             type=id3.PictureType.COVER_FRONT,
                             desc='Front cover',
                             data=data))
        else:
            # In practice, this is unsupported by most media players
            # But there's no reason not to do it
            audio.tags.add(id3.APIC(data=url, mime='-->'))

    audio.save()
Exemple #12
0
def tag_mp3(filename, title, artwork=None):
    """
    Adds ID3 tags to a file.

    Args:
        filename (str): The name of the MP3 file that needs tagging.
        title (str): The text to be used as the ID3 title.
        artwork (str): The naem of the image file to be attached as artwork.
            Defaults to None.
    """

    audio = MP3(filename)
    duration = audio.info.length
    tags = id3.ID3()

    tags['TLEN'] = id3.TLEN(encoding=3, text=str(int(duration * 1000)))

    if title:
        tags['TIT2'] = id3.TIT2(encoding=3, text=[title])

    if artwork:
        mimetype, encoding = guess_type(artwork)
        if mimetype:
            with open(artwork, 'rb') as f:
                tags['APIC'] = id3.APIC(encoding=0,
                                        mime=mimetype,
                                        type=9,
                                        data=f.read())

    tags.update_to_v23()
    tags.save(filename, v1=1, v2_version=3, padding=lambda info: 0)
def init(filename):
    audio = mp3.MP3(filename)
    print(int(audio.info.length), end='')

    tags = id3.ID3(filename, v2_version=3)
    available_tags = {
        'TIT2': 'Title',
        'APIC': 'Artwork',
        'TPE1': 'Artist',
        'TPE2': 'AlbumArtist',
        'TALB': 'Album',
        'TYER': 'Year',
        'TRCK': 'Track',
        'TPOS': 'Disc',
        'USLT': 'Lyric',
        'TCON': 'Genre',
    }
    save_tags = []
    delete_tags = []
    for tag_name in tags:
        if tag_name[:4] in available_tags.keys():
            tag = tags.getall(tag_name)
            if tag_name[:4] != 'APIC':
                tag[0].encoding = id3.Encoding.UTF16
            tag = [tag[0]]
            save_tags.append((tag_name, tag))
        else:
            delete_tags.append(tag_name)

    for tag in save_tags:
        tags.setall(tag[0], tag[1])
    for tag_name in delete_tags:
        tags.delall(tag_name)

    tags.save(v1=id3.ID3v1SaveOptions.REMOVE, v2_version=3)
Exemple #14
0
async def _write_tag(client: api.API, file_path: pathlib.Path, song: api.Song):
    audio = id3.ID3(file_path)
    audio.add(id3.TIT2(encoding=id3.Encoding.UTF8, text=song.name))
    audio.add(id3.TPE1(encoding=id3.Encoding.UTF8, text=song.artist))
    audio.add(id3.TALB(encoding=id3.Encoding.UTF8, text=song.album))

    if song.lyric:
        audio.add(
            id3.ULT(
                encoding=id3.Encoding.UTF8,
                lang='eng',
                desc=song.name,
                text=song.lyric,
            ))

    if song.pic_url:
        try:
            resp = await client.request('GET', song.pic_url)
            data = await resp.read()
        except (aiohttp.ClientError, asyncio.TimeoutError):
            pass
        else:
            audio.add(
                id3.APIC(
                    encoding=id3.Encoding.UTF8,
                    mime='image/jpeg',
                    type=id3.PictureType.COVER_FRONT,
                    desc='Front cover',
                    data=data,
                ))

    try:
        audio.save()
    except mutagen.MutagenError:
        pass
Exemple #15
0
    def read_meta(self):
        """
            Reads some metadata from the audiobook.
        """
        import mutagen
        from mutagen import id3

        artist_name = director_name = project = funded_by = ''
        if self.type == 'mp3':
            try:
                audio = id3.ID3(self.file.path)
                artist_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE1'))
                director_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE3'))
                project = ", ".join([t.data for t in audio.getall('PRIV') 
                        if t.owner=='wolnelektury.pl?project'])
                funded_by = ", ".join([t.data for t in audio.getall('PRIV') 
                        if t.owner=='wolnelektury.pl?funded_by'])
            except:
                pass
        elif self.type == 'ogg':
            try:
                audio = mutagen.File(self.file.path)
                artist_name = ', '.join(audio.get('artist', []))
                director_name = ', '.join(audio.get('conductor', []))
                project = ", ".join(audio.get('project', []))
                funded_by = ", ".join(audio.get('funded_by', []))
            except:
                pass
        else:
            return {}
        return {'artist_name': artist_name, 'director_name': director_name,
                'project': project, 'funded_by': funded_by}
    def set_tags(self, audio):
        try:
            id3_dict = id3.ID3(self.audio_file)
        except id3.ID3NoHeaderError:
            id3_dict = id3.ID3()

        def embed_image(data):
            id3_dict.add(
                id3.APIC(encoding=3,
                         mime='image/jpeg',
                         type=3,
                         desc='Front Cover',
                         data=data))

        self.save_cover_image(embed_image)

        if self.album() is not None:
            id3_dict.add(id3.TALB(text=[self.album()], encoding=3))

        id3_dict.add(id3.TIT2(text=[self.title()], encoding=3))
        id3_dict.add(id3.TPE1(text=[self.artists()], encoding=3))

        if self.album_artist() is not None:
            id3_dict.add(id3.TPE2(text=[self.album_artist()], encoding=3))

        id3_dict.add(id3.TDRC(text=[self.year()], encoding=3))
        id3_dict.add(id3.TPOS(text=[self.disc_idx_and_total()], encoding=3))
        id3_dict.add(id3.TRCK(text=[self.track_idx_and_total()], encoding=3))

        if self.comment() is not None:
            id3_dict.add(id3.COMM(text=[self.comment()], encoding=3))

        if self.grouping() is not None:
            id3_dict.add(id3.TIT1(text=[self.grouping()], encoding=3))

        if self.genres() is not None:
            tcon_tag = id3.TCON(encoding=3)
            tcon_tag.genres = self.genres()
            id3_dict.add(tcon_tag)

        if self.args.id3_v23:
            id3_dict.update_to_v23()
            id3_dict.save(self.audio_file, v2_version=3, v23_sep='/')
            id3_dict.version = (2, 3, 0)
        else:
            id3_dict.save(self.audio_file)
        audio.tags = id3_dict
Exemple #17
0
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'] = 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
Exemple #18
0
    def id3_art(self, mp3_file):

        song = mid3.ID3(mp3_file)

        tag = mid3.APIC(encoding=3, mime='image/jpeg', type=3,
                        desc="Front Cover", data=self.art_data)
        song.add(tag)
        song.save()
Exemple #19
0
 def mp3info(self):
     """ MP3(ID3)の曲情報を取得 """
     self.tags = mp3.MP3(self.filepath).tags
     # ID3タグが存在しない場合
     if self.tags == None:
         # 空のID3オブジェクトを作成
         self.tags = id3.ID3()
     self.id3info()
Exemple #20
0
    def __read_metadata_from_mp3_file(self, path_to_mp3_file: str) -> None:
        self.listener.read_metadata_started()
        with open(path_to_mp3_file, "rb") as mp3_file:
            try:
                tags = id3.ID3(mp3_file)
            except id3.ID3NoHeaderError:
                tags = id3.ID3()

        podcast_title = self.__get_podcast_name_from_id3_tags(tags)
        episode_title = self.__get_episode_title_from_id3_tags(tags)
        episode_number = self.__get_episode_number_from_id3_tags(tags)
        chapters = self.__get_chapters_from_id3_tags(tags)

        self.listener.read_metadata_complete(
            MetaData(podcast_title=podcast_title,
                     episode_title=episode_title,
                     episode_number=episode_number,
                     chapters=chapters))
Exemple #21
0
        def set_id3_tags_raw(audio, audio_file):
            try:
                id3_dict = id3.ID3(audio_file)
            except id3.ID3NoHeaderError:
                id3_dict = id3.ID3()

            def embed_image():
                id3_dict.add(
                    id3.APIC(encoding=3,
                             mime='image/jpeg',
                             type=3,
                             desc='Front Cover',
                             data=image.data))

            save_cover_image(embed_image)

            if album is not None:
                id3_dict.add(
                    id3.TALB(text=[tag_to_ascii(track.album.name, album)],
                             encoding=3))
            id3_dict.add(
                id3.TIT2(text=[tag_to_ascii(track.name, title)], encoding=3))
            id3_dict.add(
                id3.TPE1(text=[tag_to_ascii(track.artists[0].name, artist)],
                         encoding=3))
            id3_dict.add(id3.TDRC(text=[str(track.album.year)], encoding=3))
            id3_dict.add(
                id3.TPOS(text=[idx_of_total_str(track.disc, num_discs)],
                         encoding=3))
            id3_dict.add(
                id3.TRCK(text=[idx_of_total_str(track.index, num_tracks)],
                         encoding=3))
            if args.comment is not None:
                id3_dict.add(
                    id3.COMM(text=[tag_to_ascii(args.comment[0], comment)],
                             encoding=3))
            if genres is not None and genres:
                tcon_tag = id3.TCON(encoding=3)
                tcon_tag.genres = genres if args.ascii_path_only \
                    else genres_ascii
                id3_dict.add(tcon_tag)

            id3_dict.save(audio_file)
            audio.tags = id3_dict
Exemple #22
0
def track_tagger(track_path, title, artist, album, cover_path):
    track = mp3.EasyMP3(track_path)
    track['title'] = title
    track['artist'] = artist
    track['album'] = album
    track.save()
    cover_image = open(cover_path, 'rb').read()
    track = id3.ID3(track_path)
    track.add(id3.APIC(3, 'image/jpeg', 3, u'Cover', cover_image))
    track.save()
    remove(cover_path)
Exemple #23
0
 def write_tags(self):
     """Write all ID3v2.4 tags by mapping dub2id3_dict dictionnary with the
         respect of mutagen classes and methods"""
     from mutagen import id3  
     id3 = id3.ID3(self.dest)
     for tag in self.metadata.keys():
         if tag in self.dub2id3_dict.keys():
             frame_text = self.dub2id3_dict[tag]
             value = self.metadata[tag]
             frame = mutagen.id3.Frames[frame_text](3,value)
             id3.add(frame)
     id3.save()
Exemple #24
0
 def _check_id3version(self, files):
     check = True
     for item in files:
         message = '"{}": no suitable tag'.format(item)
         try:
             song = id3.ID3(item)
         except (MutagenError, OSError):
             check = False
             print(message)
         else:
             if song.version[0] == 1:
                 check = False
                 print(message)
     return check
Exemple #25
0
    def save(self):
        if self.clr:
            for file in self.audiofiles:
                tmp = mid3.ID3(file)
                tmp.clear()
                tmp.add(mid3.TIT2(text=""))  # title frame
                tmp.add(mid3.TPE1(text=""))  # artist frame
                tmp.add(mid3.TALB(text=""))  # album frame
                tmp.add(mid3.TPE2(text=""))  # album artist frame
                tmp.add(mid3.TCOM(text=""))  # composer frame
                tmp.add(mid3.TCON(text=""))  # genre frame
                tmp.add(mid3.TDRC(text=""))  # date frame
                tmp.add(mid3.TRCK(text=""))  # tracknumber frame
                tmp.add(mid3.TPOS(text=""))  # discnumber frame
                tmp.add(mid3.TBPM(text=""))  # bpm frame
                tmp.save()

        if self.artwork:
            with open(self.artwork, 'rb') as albumart:
                for file in self.audiofiles:
                    tmp = mid3.ID3(file)
                    tmp['APIC'] = mid3.APIC(
                        encoding=3,
                        mime='image/jpeg',
                        type=3, desc=u'Cover',
                        data=albumart.read()
                    )
                    tmp.save()
                    albumart.seek(0)

        for file in self.audiofiles:
            tmp = EasyID3(file)
            for tag in self.__sets:
                if self.__sets[tag]:
                    tmp[tag] = self.__sets[tag]
                    tmp.save()
def addpic(mp3file, imgfile):
    type = None
    if imgfile.endswith('png'):
        type = "image/png"
    elif imgfile.endswith('jpg') or imgfile.endswith('jpeg'):
        type = "image/jpeg"
    else:
        sys.exit(1)
    tag = id3.ID3(mp3file, v2_version=3)
    with open(imgfile).read() as f:
        tag.add(
            id3.APIC(encoding=id3.Encoding.UTF16,
                     mime=type,
                     type=id3.PictureType.COVER_FRONT,
                     data=f.read()))
    tag.save()
Exemple #27
0
    def id3_tag(self, a_file):
        """ Similar to the function above, this function adds metadata to a
        an ID3 tag within an MP3 file. Prior to application, it sorts out a
        few formatting tidbits on how the tracks/total tracks and disc/total
        discs are applied.
        """

        title, extension = os.path.splitext(a_file)
        info_dict = self.info_dict

        if extension == '.mp3':
            song = mid3.ID3(a_file)
        else:
            print("%s format not permitted by id3_paste" % extension)

        # Remove any pre-existing tags
        song.delete()

        try:
            id3_discs = "%s/%s" % (info_dict['disc'], info_dict['total_discs'])
        except KeyError:
            id3_discs = '1/1'

        try:
            id3_track = "%s/%s" % (self.track_number.zfill(2),
                                   str(info_dict['total_tracks']).zfill(2))
        except KeyError:
            id3_track = self.track_number

        transfer_dictionary = {
            'TALB': info_dict['album'],
            'TPE1': info_dict['album_artist'],
            'TPE2': info_dict['artist'],
            'TDRL': info_dict['date'][:4],
            'TPUB': info_dict['label'],
            'TCON': info_dict['genre'],
            'TIT2': self.track_title,
            'TRCK': id3_track,
            'TPOS': id3_discs
        }

        for tag in transfer_dictionary:
            exec_string = 'song.add(mid3.%s(3, text="%s"))' % (
                tag, transfer_dictionary[tag])
            exec(exec_string)

        song.save()
Exemple #28
0
    def write_metadata(self):
        """Write all ID3v2.4 tags to file from self.metadata"""
        import mutagen
        from mutagen import id3

        id3 = id3.ID3(self.filename)
        for tag in self.metadata.keys():
            value = self.metadata[tag]
            frame = mutagen.id3.Frames[tag](3, value)
            try:
                id3.add(frame)
            except:
                raise IOError('EncoderError: cannot tag "' + tag + '"')
        try:
            id3.save()
        except:
            raise IOError('EncoderError: cannot write tags')
Exemple #29
0
def load_mp3(total, dir, file):
    path = os.path.join(dir, file)
    #mfile = File(path)
    #file = File('some.mp3') # mutagen can automatically detect format and type of tags
    #artwork = file.tags['APIC:'].data # access APIC frame and grab the image
    #with open('image.jpg', 'wb') as img:
    #    img.write(artwork) # write artwork to new image
    #artwork = mfile.tags['APIC:'].data # access APIC frame and grab the image
    #with open('{0}.jpg'.format(path), 'wb') as img:
    #    img.write(artwork) # write artwork to new image
    audio = MP3(path)
    print audio.info.length #, audio.info.bitrate
    m = id3.ID3(path)

    data = m.get('TXXX:OverDrive MediaMarkers')
    if not data:
        print "Can't find TXXX data point for {0}".format(file)
        print m.keys()
        return
    info = data.text[0].encode("ascii", "ignore")
    #print info
    file_chapters = re.findall(r"<Name>\s*([^>]+?)\s*</Name><Time>\s*([\d:.]+)\s*</Time>", info, re.MULTILINE)
    chapters = []
    for chapter in file_chapters:
        (name, length) = chapter
        name = re.sub(r'^"(.+)"$', r'\1', name)
        name = re.sub(r'^\*(.+)\*$', r'\1', name)
        name = re.sub(r'\s*\([^)]*\)$', '', name) # ignore any sub-chapter markers from Overdrive
        name = re.sub(r'\s+\(?continued\)?$', '', name) # ignore any sub-chapter markers from Overdrive
        name = re.sub(r'\s+-\s*$', '', name)      # ignore any sub-chapter markers from Overdrive
        name = re.sub(r'^Dis[kc]\s+\d+\W*$', '', name)  # ignore any disk markers from Overdrive
        name = name.strip()
        t_parts = list(length.split(':'))
        t_parts.reverse()
        seconds = total + float(t_parts[0])
        if len(t_parts) > 1:
            seconds += (int(t_parts[1]) * 60)
        if len(t_parts) > 2:
            seconds += (int(t_parts[2]) * 60 * 60)
        chapters.append([name, seconds])
        print name, seconds
        #chapters = re.search(r'(\w+)', info)
    #print repr(chapters)
    return (total + audio.info.length, chapters)
    return
    def __init__(self, filename, use_id3_v23, keep_id3_v1=False):
        from mutagen import id3
        self.obj = None
        self.filename = filename
        self.use_id3_v23 = use_id3_v23
        self.keep_id3_v1 = keep_id3_v1
        self.map = {
            'album': 'TALB',
            'bpm': 'TBPM',
            'composer': 'TCOM',
            'copyright': 'TCOP',
            'encodedby': 'TENC',
            'lyricist': 'TEXT',
            'length': 'TLEN',
            'media': 'TMED',
            'mood': 'TMOO',
            'title': 'TIT2',
            'version': 'TIT3',
            'artist': 'TPE1',
            'performer': 'TPE2',
            'conductor': 'TPE3',
            'arranger': 'TPE4',
            'discnumber': 'TPOS',
            'organization': 'TPUB',
            'tracknumber': 'TRCK',
            'author': 'TOLY',
            'isrc': 'TSRC',
            'discsubtitle': 'TSST',
            'language': 'TLAN',
            # handled separately
            'website': None,
            # aliases
            'description': 'TSST',
            'comment': 'TIT3',
            'albumartist': 'TPE2'}

        try:
            self._load()
        except mutagen.id3._util.ID3NoHeaderError:
            # the id3 tag doesn't exist yet; let's just add it now.
            self.obj = id3.ID3()
            self['title'] = ''
            self.save()
            self._load()