Example #1
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
Example #2
0
        def set_id3_tags(audio):
            # add ID3 tag if it doesn't exist
            audio.add_tags()

            def embed_image(data):
                audio.tags.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:
                audio.tags.add(
                    id3.TALB(text=[tag_to_ascii(track.album.name, album)],
                             encoding=3))
            audio.tags.add(
                id3.TIT2(text=[tag_to_ascii(track.name, title)],
                         encoding=3))
            audio.tags.add(
                id3.TPE1(text=[tag_to_ascii(artists, artists_ascii)],
                         encoding=3))
            if album_artist is not None:
                audio.tags.add(
                    id3.TPE2(text=[tag_to_ascii(
                                       track.album.artist.name, album_artist)],
                             encoding=3))
            audio.tags.add(id3.TDRC(text=[str(track.album.year)],
                                    encoding=3))
            audio.tags.add(
                id3.TPOS(text=[idx_of_total_str(track.disc, num_discs)],
                         encoding=3))
            audio.tags.add(
                id3.TRCK(text=[idx_of_total_str(track.index, num_tracks)],
                         encoding=3))
            if args.comment is not None:
                audio.tags.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
                audio.tags.add(tcon_tag)

            if args.id3_v23:
                audio.tags.update_to_v23()
                audio.save(v2_version=3, v23_sep='/')
                audio.tags.version = (2, 3, 0)
            else:
                audio.save()
Example #3
0
 def test_encoding(self):
     tags = compatid3.CompatID3()
     tags.add(id3.TALB(encoding=2, text="abc"))
     tags.add(id3.TIT2(encoding=3, text="abc"))
     tags.update_to_v23()
     self.assertEqual(tags["TALB"].encoding, 1)
     self.assertEqual(tags["TIT2"].encoding, 1)
Example #4
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')
Example #5
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)
Example #6
0
def write_id3(mp3_file, track, cover=None):
    t = mp3.Open(mp3_file)
    if not t.tags:
        t.add_tags()

    album = track['albums'][0]

    t_add = t.tags.add
    t_add(id3.TIT2(encoding=3, text=track['title']))
    t_add(id3.TPE1(encoding=3, text=track['artists']))
    t_add(id3.TCOM(encoding=3, text=track[FLD_COMPOSERS]))
    t_add(id3.TALB(encoding=3, text=album['title']))

    if 'labels' in album:
        t_add(id3.TPUB(encoding=3,
                       text=', '.join(l['name'] for l in album['labels'])))
    if FLD_TRACKNUM in track:
        tnum = '{}/{}'.format(track[FLD_TRACKNUM], album['trackCount'])
        t_add(id3.TRCK(encoding=3, text=tnum))
    if FLD_VOLUMENUM in album:
        t_add(id3.TPOS(encoding=3, text=str(album[FLD_VOLUMENUM])))
    if 'year' in album:
        t_add(id3.TDRC(encoding=3, text=str(album['year'])))
    if args.genre:
        t_add(id3.TCON(encoding=3, text=album['genre'].title()))
    if cover:
        t_add(id3.APIC(encoding=3, desc='', mime=cover.mime,
                       type=3, data=cover.data))

    t.tags.update_to_v23()
#id3.ID3v1SaveOptions.CREATE = 2
    t.save(v1=2, v2_version=3)
Example #7
0
def write_mp3_chapters(audio, chapters):
    z = 0
    chapter_ids = []
    for chapter in chapters:
        z += 1
        chap_id = 'chap%s' % str(z).zfill(4)
        start = get_milliseconds(chapter['start'])
        stop = get_milliseconds(chapter['stop'])
        embeded_elements = []
        for tag in chapter:
            if tag == 'title':
                embeded_elements.append(id3.TIT2(encoding=3,
                                                 text=chapter[tag]))
            elif tag == 'description':
                embeded_elements.append(id3.TIT3(encoding=3,
                                                 text=chapter[tag]))
            elif tag == 'image':
                image = get_mp3_coverart(chapter[tag])
                image = id3.APIC(3, 'image/jpeg', 3, '', image)
                embeded_elements.append(image)
        chap = CHAP(element_id=chap_id, start=start, stop=stop,
              embeded_frames=embeded_elements)
        audio[chap_id] = chap
        chapter_ids.append(chap_id)
    ctoc = CTOC('ctoc0001', False, True, chapter_ids)
    audio['ctoc0001'] = ctoc
Example #8
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
Example #9
0
    def write_tags(self):
        """Write all ID3v2.4 tags by mapping dub2id3_dict dictionnary with the
            respect of mutagen classes and methods"""

        self.sourceobj.add_tags()
        self.sourceobj.tags['TIT2'] = id3.TIT2(encoding=2, text=u'text')
        self.sourceobj.save()
        '''
        # media_id3 = id3.ID3(self.media)
        # for tag in self.metadata.keys():
            # if tag in self.dub2id3_dict:
                # frame_text = self.dub2id3_dict[tag]
                # value = self.metadata[tag]
                # frame = mutagen.id3.Frames[frame_text](3,value)
            # try:
                # media_id3.add(frame)
            # except:
                # raise IOError('ExporterError: cannot tag "'+tag+'"')

        # try:
            # media_id3.save()
        # except:
            # raise IOError('ExporterError: cannot write tags')
        '''

        media = id3.ID3(self.media)
        media.add(
            id3.TIT2(encoding=3, text=self.metadata['title'].decode('utf8')))
        media.add(
            id3.TP1(encoding=3, text=self.metadata['artist'].decode('utf8')))
        media.add(
            id3.TAL(encoding=3, text=self.metadata['album'].decode('utf8')))
        media.add(
            id3.TDRC(
                encoding=3,
                text=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
        media.add(
            id3.TCO(encoding=3, text=self.metadata['genre'].decode('utf8')))
        try:
            media.save()
        except:
            raise IOError('ExporterError: cannot write tags')
Example #10
0
    def __get_tags(metadata: MetaData) -> id3.ID3:
        tags = id3.ID3()

        if metadata.podcast_title:
            tags.add(
                id3.TPE1(encoding=id3.Encoding.LATIN1,
                         text=metadata.podcast_title))

        if metadata.episode_title:
            tags.add(
                id3.TIT2(encoding=id3.Encoding.LATIN1,
                         text=metadata.episode_title))

        if metadata.episode_number:
            tags.add(
                id3.TRCK(encoding=id3.Encoding.LATIN1,
                         text=str(metadata.episode_number)))

        if metadata.chapters:
            toc: List[str] = [
                f"chp{index}" for index in range(len(metadata.chapters))
            ]
            tags.add(
                id3.CTOC(encoding=id3.Encoding.LATIN1,
                         element_id="toc",
                         flags=id3.CTOCFlags.TOP_LEVEL | id3.CTOCFlags.ORDERED,
                         child_element_ids=toc,
                         sub_frames=[]))

            for idx, chapter in enumerate(metadata.chapters):
                tags.add(
                    id3.CHAP(encoding=id3.Encoding.LATIN1,
                             element_id=f"chp{idx}",
                             start_time=chapter.start,
                             end_time=chapter.end,
                             sub_frames=[
                                 id3.TIT2(encoding=id3.Encoding.LATIN1,
                                          text=chapter.name)
                             ]))

        return tags
Example #11
0
    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
Example #12
0
def compiletracl(tracl):
    rawfile = File("%s.mp3" % tracl['id'])

    rawfile['TIT2'] = id3.TIT2(encoding=3, text=tracl['title'])
    rawfile['TALB'] = id3.TALB(encoding=3, text=tracl['album'])
    rawfile['TPE1'] = id3.TPE1(encoding=3, text=tracl['artist'])
    rawfile['TCON'] = id3.TCON(encoding=3, text=tracl['genre'])
    rawfile['TYER'] = id3.TYER(encoding=3, text=tracl['year'])
    rawfile['TRCK'] = id3.TRCK(encoding=3, text=tracl['len'])
    rawfile['WOAS'] = id3.WOAS(encoding=3, text=tracl['link'])

    rawfile['APIC'] = id3.APIC(encoding=3,
                               type=3,
                               mime='image/jpeg',
                               desc='Cover',
                               data=downloadcover(tracl))

    rawfile.save(v2_version=3)
Example #13
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
Example #14
0
    def set_tags(self, audio):
        # add ID3 tag if it doesn't exist
        audio.add_tags()

        def embed_image(data):
            audio.tags.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:
            audio.tags.add(id3.TALB(text=[self.album()], encoding=3))

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

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

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

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

        if self.grouping() is not None:
            audio.tags.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()
            audio.tags.add(tcon_tag)

        if self.args.id3_v23:
            audio.tags.update_to_v23()
            audio.save(v2_version=3, v23_sep='/')
            audio.tags.version = (2, 3, 0)
        else:
            audio.save()
Example #15
0
def set_id3(filename, title, artists, album):
    """
    Sets TIT2, TPE1 and TALB ID3v2 tags for filename 
    """
    print("Setting ID3 tag for " + filename)

    audio = id3.ID3(filename)

    audio.add(id3.TIT2(encoding=ENCODING, text=title))
    print("Set title " + track["name"])

    audio.add(id3.TPE1(encoding=ENCODING, text=artists))
    print("Set artists " + artists)

    audio.add(id3.TALB(encoding=ENCODING, text=album))
    print("Set album " + album)

    audio.save()
    print("Done")
def add_chapters(tags: id3.ID3, chapters: List[Tuple[int, int, str]]) -> None:
    toc = [f"chp{index}" for index in range(len(chapters))]
    tags.add(
        id3.CTOC(encoding=id3.Encoding.LATIN1,
                 element_id="toc",
                 flags=id3.CTOCFlags.TOP_LEVEL | id3.CTOCFlags.ORDERED,
                 child_element_ids=toc,
                 sub_frames=[]))

    for idx, chapter in enumerate(chapters):
        tags.add(
            id3.CHAP(encoding=id3.Encoding.LATIN1,
                     element_id=f"chp{idx}",
                     start_time=chapter[0],
                     end_time=chapter[1],
                     sub_frames=[
                         id3.TIT2(encoding=id3.Encoding.LATIN1,
                                  text=chapter[2])
                     ]))
Example #17
0
        def set_id3_tags(audio):
            # add ID3 tag if it doesn't exist
            audio.add_tags()

            def embed_image():
                audio.tags.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:
                audio.tags.add(
                    id3.TALB(text=[tag_to_ascii(track.album.name, album)],
                             encoding=3))
            audio.tags.add(
                id3.TIT2(text=[tag_to_ascii(track.name, title)], encoding=3))
            audio.tags.add(
                id3.TPE1(text=[tag_to_ascii(track.artists[0].name, artist)],
                         encoding=3))
            audio.tags.add(id3.TDRC(text=[str(track.album.year)], encoding=3))
            audio.tags.add(
                id3.TPOS(text=[idx_of_total_str(track.disc, num_discs)],
                         encoding=3))
            audio.tags.add(
                id3.TRCK(text=[idx_of_total_str(track.index, num_tracks)],
                         encoding=3))
            if args.comment is not None:
                audio.tags.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
                audio.tags.add(tcon_tag)

            audio.save()
Example #18
0
 def _write_id3v2_tag(self, file_name, step, obj):
     song = self.active_class(file_name)
     song.delete()
     song['TPE1'] = id3.TPE1(encoding=3, text=[obj.artist[step]])
     song['TALB'] = id3.TALB(encoding=3, text=[obj.album])
     if obj.genre and not obj.tgenre:
         song['TCON'] = id3.TCON(encoding=3, text=[obj.genre])
     elif obj.tgenre:
         song['TCON'] = id3.TCON(encoding=3, text=[obj.tgenre[step]])
     song['TIT2'] = id3.TIT2(encoding=3, text=[obj.title[step]])
     number = '{0}/{1}'.format(int(obj.track[step]), int(obj.track[-1]))
     song['TRCK'] = id3.TRCK(encoding=3, text=[number])
     if obj.year and not obj.tdate:
         song['TDRC'] = id3.TDRC(encoding=3, text=[obj.year])
     elif obj.tdate:
         song['TDRC'] = id3.TDRC(encoding=3, text=[obj.tdate[step]])
     song['COMM::XXX'] = id3.COMM(encoding=3,
                                  lang='XXX',
                                  desc='',
                                  text=[obj.comment])
     song.save(file_name)
Example #19
0
def tag_mp3(path_audio,path_pic,lrc,title,artist,album,disc,track,**kw):
    '''
    ref:
    http://id3.org/id3v2.3.0
    https://github.com/quodlibet/mutagen/blob/master/mutagen/id3/_frames.py
    http://help.mp3tag.de/main_tags.html
    http://code.activestate.com/recipes/577138-embed-lyrics-into-mp3-files-using-mutagen-uslt-tag/
    '''
    tags=id3.ID3()
    if path_pic:
        with open(path_pic,'rb') as f:
            tags['APIC']=id3.APIC(mime='image/jpeg',type=id3.PictureType.COVER_FRONT,data=f.read())
    for x in lrc:
        tags["USLT::"+x['lang']]=id3.USLT(text=x['text'],lang=x['lang'])
    tags['TIT2']=id3.TIT2(text=title)
    tags['TPE1']=id3.TPE1(text=artist)
    if album!=None:
        tags['TALB']=id3.TALB(text=album)
    tags['TPOS']=id3.TPOS(text=disc)
    tags['TRCK']=id3.TRCK(text=str(track))
    tags.save(path_audio)
Example #20
0
    def id3edit(self):
        """ ID3タグを編集 """

        # ID3タグ書き換え encoding: UTF-16 with BOM (1)
        self.tags['TIT2'] = id3.TIT2(encoding=1, text=self.title)
        self.tags['TALB'] = id3.TALB(encoding=1, text=self.album)
        self.tags['TPE1'] = id3.TPE1(encoding=1, text=self.artist)
        self.tags['TCON'] = id3.TCON(encoding=1, text=self.genre)
        #self.tags['TPE2'] = TPE2(encoding=1, text=self.albumartist)

        self.tags.delall('COMM')
        self.tags['COMM'] = id3.COMM(encoding=1, lang='eng', text=self.comment)

        # アートワーク書き換え
        if not self.artwork_url == '':   # アートワーク画像のURLがある場合
            # 画像読み込み
            try:
                artwork_read = urlopen(self.artwork_url).read()
            except:
                raise URLOpenError("画像を取得できません")

            # アートワーク初期化
            self.tags.delall('APIC')

            # 画像設定
            self.tags['APIC'] = id3.APIC(
                encoding=1, mime='image/jpeg', type=3, desc='Cover', data=artwork_read)

        # 保存
        self.tags.save(self.filepath)

        # 表示用アートワーク更新
        artworks = self.tags.getall('APIC')  # list
        artwork = None
        for artwork in artworks:    # 抽出
            pass
        if artwork:     # アートワーク画像が存在するか
            self.artwork = artwork.data  # type: bytes
        else:
            self.artwork = None
Example #21
0
    def tag(self, target, track):
        mp3 = MP3(os.path.join(self.workdir, target))

        if not mp3.tags:
            mp3.add_tags()

        tags = mp3.tags
        tags.add(id3.TALB(encoding=id3.Encoding.UTF8, text=self.disc.album))
        tags.add(id3.TPE1(encoding=id3.Encoding.UTF8, text=self.disc.artist))
        tags.add(id3.TIT2(encoding=id3.Encoding.UTF8, text=track.title))
        tags.add(id3.TRCK(encoding=id3.Encoding.UTF8, text=str(track.trackno)))
        tags.add(id3.TDRC(encoding=id3.Encoding.UTF8,
                          text=str(self.disc.year)))

        tpos = str(self.disc.discno)
        if self.disc.set_size > 1:
            tpos = f"{self.disc.discno}/{self.disc.set_size}"
        tags.add(id3.TPOS(encoding=id3.Encoding.UTF8, text=tpos))

        if self.disc.cover_art:
            tags.add(
                id3.APIC(encoding=id3.Encoding.UTF8, data=self.disc.cover_art))

        mp3.save()
Example #22
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()
Example #23
0
 def _write_tags(self, tags):
     for tag, value in tags.items():
         if tag == "releaseName" or tag == "release_name" or tag == "TALB":
             self._add_tag(id3.TALB(encoding=UTF_8, text=value))
         elif tag == "front_cover" or tag == "APIC_FRONT":
             mime, desc, data = value
             self._add_tag(id3.APIC(UTF_8, mime, FRONT_COVER, desc, data))
         elif tag == "backCover" or tag == "APIC_BACK":
             mime, desc, data = value
             self._add_tag(id3.APIC(UTF_8, mime, BACK_COVER, desc, data))
         elif tag == "lead_performer" or tag == "TPE1":
             self._add_tag(id3.TPE1(encoding=UTF_8, text=value))
         elif tag == "lead_performer_region" or tag == "TXXX_LEAD_PERFORMER_REGION":
             self._add_tag(
                 id3.TXXX(encoding=UTF_8,
                          desc="LEAD-PERFORMER-REGION:UN/LOCODE",
                          text=value))
         elif tag == "lead_performer_date_of_birth" or tag == "TXXX_LEAD_PERFORMER_DATE_OF_BIRTH":
             self._add_tag(
                 id3.TXXX(encoding=UTF_8,
                          desc="LEAD-PERFORMER-DATE-OF-BIRTH",
                          text=value))
         elif tag == "guestPerformers" or tag == "TMCL":
             self._add_tag(id3.TMCL(encoding=UTF_8, people=value))
         elif tag == "label_name" or tag == "TOWN":
             self._add_tag(id3.TOWN(encoding=UTF_8, text=value))
         elif tag == "catalogNumber" or tag == "TXXX_CATALOG_NUMBER":
             self._add_tag(
                 id3.TXXX(encoding=UTF_8, desc="Catalog Number",
                          text=value))
         elif tag == "upc" or tag == "TXXX_UPC":
             """ Deprecated and replaced with BARCODE """
             self._add_tag(id3.TXXX(encoding=UTF_8, desc="UPC", text=value))
         elif tag == "barcode" or tag == "TXXX_BARCODE":
             self._add_tag(
                 id3.TXXX(encoding=UTF_8, desc="BARCODE", text=value))
         elif tag == "recording_time" or tag == "TDRC":
             self._add_tag(
                 id3.TDRC(encoding=UTF_8, text=[id3.ID3TimeStamp(value)]))
         elif tag == "releaseTime" or tag == "TDRL":
             self._add_tag(
                 id3.TDRL(encoding=UTF_8, text=[id3.ID3TimeStamp(value)]))
         elif tag == "originalReleaseTime" or tag == "TDOR":
             self._add_tag(
                 id3.TDOR(encoding=UTF_8, text=[id3.ID3TimeStamp(value)]))
         elif tag == "tagging_time" or tag == "TDTG":
             self._add_tag(
                 id3.TDTG(encoding=UTF_8, text=[id3.ID3TimeStamp(value)]))
         elif tag == "recordingStudios" or tag == "TXXX_RECORDING_STUDIO":
             self._add_tag(
                 id3.TXXX(encoding=UTF_8,
                          desc="Recording Studio",
                          text=value))
         elif tag == "TIPL":
             self._add_tag(id3.TIPL(encoding=UTF_8, people=value))
         elif tag == "comments" or tag == "COMM":
             text, lang = value
             self._add_tag(
                 id3.COMM(encoding=UTF_8, text=text, desc="", lang=lang))
         elif tag == "track_title" or tag == "TIT2":
             self._add_tag(id3.TIT2(encoding=UTF_8, text=value))
         elif tag == "version_info" or tag == "TPE4":
             self._add_tag(id3.TPE4(encoding=UTF_8, text=value))
         elif tag == "featured_guest" or tag == "TXXX_FEATURED_GUEST":
             self._add_tag(
                 id3.TXXX(encoding=UTF_8, desc="Featured Guest",
                          text=value))
         elif tag == "lyricist" or tag == "TEXT":
             self._add_tag(id3.TEXT(encoding=UTF_8, text=value))
         elif tag == "composer" or tag == "TCOM":
             self._add_tag(id3.TCOM(encoding=UTF_8, text=value))
         elif tag == "publisher" or tag == "TPUB":
             self._add_tag(id3.TPUB(encoding=UTF_8, text=value))
         elif tag == "isrc" or tag == "TSRC":
             self._add_tag(id3.TSRC(encoding=UTF_8, text=value))
         elif tag == "labels" or tag == "TXXX_TAGS":
             self._add_tag(id3.TXXX(encoding=UTF_8, desc="Tags",
                                    text=value))
         elif tag == "isni" or tag == "TXXX_ISNI_Joel_Miller":
             self._add_tag(
                 id3.TXXX(encoding=UTF_8,
                          desc="ISNI:Joel Miller",
                          text=value))
         elif tag == "TXXX_ISNI_Rebecca_Ann_Maloy":
             self._add_tag(
                 id3.TXXX(encoding=UTF_8,
                          desc="ISNI:Rebecca Ann Maloy",
                          text=value))
         elif tag == "TXXX_IPI_Joel_Miller":
             self._add_tag(
                 id3.TXXX(encoding=UTF_8,
                          desc="IPI:Joel Miller",
                          text=value))
         elif tag == "TXXX_IPI_Rebecca_Ann_Maloy":
             self._add_tag(
                 id3.TXXX(encoding=UTF_8,
                          desc="IPI:Rebecca Ann Maloy",
                          text=value))
         elif tag == "TXXX_ISNI":
             self._add_tag(id3.TXXX(encoding=UTF_8, desc="ISNI",
                                    text=value))
         elif tag == "iswc" or tag == "TXXX_ISWC":
             self._add_tag(id3.TXXX(encoding=UTF_8, desc="ISWC",
                                    text=value))
         elif tag == "lyrics" or tag == "USLT":
             text, lang = value
             self._add_tag(
                 id3.USLT(encoding=UTF_8, text=text, desc="", lang=lang))
         elif tag == "language" or tag == "TLAN":
             self._add_tag(id3.TLAN(encoding=UTF_8, text=value))
         elif tag == "primary_style" or tag == "TCON":
             self._add_tag(id3.TCON(encoding=UTF_8, text=value))
         elif tag == "compilation" or tag == "TCMP":
             self._add_tag(id3.TCMP(encoding=UTF_8, text=value))
         elif tag == "tagger" or tag == "TXXX_TAGGER":
             self._add_tag(
                 id3.TXXX(encoding=UTF_8, desc="TAGGER", text=value))
         elif tag == "TXXX_Tagger":
             """ Deprecated and replaced with separate TAGGER and VERSION tags """
             self._add_tag(
                 id3.TXXX(encoding=UTF_8, desc="Tagger", text=value))
         elif tag == "tagger_version" or tag == "TXXX_TAGGER_VERSION":
             self._add_tag(
                 id3.TXXX(encoding=UTF_8, desc="TAGGER_VERSION",
                          text=value))
         elif tag == "TXXX_Tagging_Time":
             """ Deprecated and replaced with TAGGING_TIME """
             self._add_tag(
                 id3.TXXX(encoding=UTF_8, desc="Tagging Time", text=value))
         elif tag == "TXXX_TAGGING_TIME":
             """ Deprecated and replaced with TDTG """
             self._add_tag(
                 id3.TXXX(encoding=UTF_8, desc="TAGGING_TIME", text=value))
         elif tag == "TXXX_PRODUCTION_COMPANY":
             self._add_tag(
                 id3.TXXX(encoding=UTF_8,
                          desc="PRODUCTION-COMPANY",
                          text=value))
         elif tag == "TXXX_PRODUCTION_COMPANY_REGION":
             self._add_tag(
                 id3.TXXX(encoding=UTF_8,
                          desc="PRODUCTION-COMPANY-REGION:UN/LOCODE",
                          text=value))
         elif tag == "TXXX_RECORDING_STUDIO_REGION":
             self._add_tag(
                 id3.TXXX(encoding=UTF_8,
                          desc="RECORDING-STUDIO-REGION:UN/LOCODE",
                          text=value))
         elif tag == "TXXX_RECORDING_STUDIO_ADDRESS":
             self._add_tag(
                 id3.TXXX(encoding=UTF_8,
                          desc="RECORDING-STUDIO-ADDRESS",
                          text=value))
         elif tag == "TRCK":
             self._add_tag(id3.TRCK(encoding=UTF_8, text=value))
         else:
             raise AssertionError("Knows nothing about '{0}'".format(tag))
Example #24
0
                    result['genre'] = result['genre'][each]['TEXT']
                    break
            else:
                if not result['genre']:
                    result['genre'] = 'Other'
                else:
                    print(
                        "Failed with no appropriate genre found for '{0} - {1}':\n{2}"
                        .format(artist, music, result['genre']))
                    continue

            if 'TALB' in tags and str(
                    tags['TALB']) and str(tags['TALB']) != 'Unknown Album':
                result['album_title'] = str(tags['TALB'])

            tags['TIT2'] = id3.TIT2(encoding=3, text=u'{0}'.format(music))
            tags['TALB'] = id3.TALB(encoding=3,
                                    text=u'{0}'.format(result['album_title']))
            tags['TPE1'] = id3.TPE1(encoding=3,
                                    text=u'{0}'.format(real_artist))
            tags['TCON'] = id3.TCON(encoding=3,
                                    text=u'{0}'.format(result['genre']))
            tags['TDRC'] = id3.TDRC(encoding=3,
                                    text=u'{0}'.format(result['album_year']))
            tags['TRCK'] = id3.TRCK(encoding=3,
                                    text=u'{0}'.format(result['track_number']))
            if album_art:
                tags['APIC'] = id3.APIC(
                    encoding=3,
                    mime='image/png'
                    if '.png' in result['album_art_url'] else 'image/jpeg',
Example #25
0
     del trackIDs[0]
     continue
 print("Downloading song " + str(i + 1) + " of " + str(totalTracks) + ": " +
       id3Title + " by " + id3Artist)
 try:
     url = api.get_stream_url(trackIDs[0])
     urlretrieve(url, filePath)
 except:
     print("Error occurred downloading trackID " + trackIDs[0] +
           ". Skipping...")
     del trackIDs[0]
     continue
 errorTrack = 0
 mp3File = File(filePath)
 mp3File.add_tags()
 mp3File.tags.add(id3.TIT2(encoding=3, text=id3Title))
 mp3File.tags.add(id3.TALB(encoding=3, text=id3Album))
 mp3File.tags.add(id3.TPE1(encoding=3, text=id3Artist))
 mp3File.tags.add(id3.TPE2(encoding=3, text=id3AlbumArtist))
 mp3File.tags.add(id3.TCOM(encoding=3, text=id3Composer))
 if id3Genre:
     mp3File.tags.add(id3.TCON(encoding=3, text=id3Genre))
 if id3Year:
     mp3File.tags.add(id3.TYER(encoding=3, text=id3Year))
 mp3File.tags.add(id3.TRCK(encoding=3, text=id3TrackNumber))
 mp3File.tags.add(id3.TPOS(encoding=3, text=id3DiscNumber))
 if id3AlbumCover:
     mp3File.tags.add(
         id3.APIC(mime='image/jpeg',
                  type=3,
                  desc=u'Cover',
Example #26
0
 def setTitle(self, _value):
     self.isSave = True
     self.tags["TIT2"] = id3.TIT2(
         encoding=3, text=self.correctValuesForMusicTagType(_value))
def add_episode_title(tags: id3.ID3, episode_name: str) -> None:
    tags.add(id3.TIT2(encoding=id3.Encoding.LATIN1, text=episode_name))
def add_id3_data_to_mp3(mp3_path,
                        track_name,
                        artist_name,
                        album_name,
                        genres,
                        cover_art_path=None,
                        remove_cover_art=True):
    mp3_path = Path(mp3_path).resolve()
    cover_art_path = Path(cover_art_path).resolve()

    try:
        mp3_meta = id3.ID3(mp3_path)
    except mutagen.id3.ID3NoHeaderError:
        mp3_meta = mutagen.File(mp3_path, easy=True)
        mp3_meta.add_tags()
        mp3_meta.save()
        mp3_meta = id3.ID3(mp3_path)

    # track
    mp3_meta.add(id3.TIT2(text=track_name, encoding=3))
    mp3_meta.add(id3.TSOT(text=track_name, encoding=3))

    # artist
    mp3_meta.add(id3.TOPE(text=artist_name, encoding=3))
    mp3_meta.add(id3.TPE1(text=artist_name, encoding=3))
    mp3_meta.add(id3.TSO2(text=artist_name, encoding=3))

    # album
    mp3_meta.add(id3.TALB(text=album_name, encoding=3))
    mp3_meta.add(id3.TOAL(text=album_name, encoding=3))
    mp3_meta.add(id3.TSOA(text=album_name, encoding=3))

    # genre
    if len(genres) > 0:
        mp3_meta.add(id3.TCON(text=genres[0], encoding=3))

    # comment
    mp3_meta.add(
        id3.COMM(text='finessed', desc=u'finessed', encoding=3, lang='ENG'))

    # cover art
    if cover_art_path:
        ext = Path(cover_art_path).suffix[1:]
        just_name = Path(cover_art_path).stem
        parent_dir = Path(cover_art_path).parent

        if ext == 'jpg' or ext == 'jpeg' or ext == 'webp' or ext == 'png':
            if ext == 'jpg' or ext == 'jpeg' or ext == 'webp':
                with Image.open(cover_art_path).convert("RGB") as cover_art:
                    cover_art.save(f"{parent_dir / just_name}.png", "png")
                    og_cover_art = str(cover_art_path)
                    cover_art_path = f"{parent_dir / just_name}.png"

            with open(cover_art_path, 'rb') as cover_art:
                mp3_meta.add(
                    id3.APIC(encoding=3,
                             mime=f'image/png',
                             type=3,
                             desc='youtube thumbnail',
                             data=cover_art.read()))

            if remove_cover_art:
                Path(cover_art_path).unlink()
                Path(og_cover_art).unlink()

    mp3_meta.save()
Example #29
0
def title(metadata):
    return id3.TIT2(text=_title_text(metadata))