예제 #1
0
def handle_audio_file(audio_file):
    print('Handling audio file', audio_file)
    extension = os.path.splitext(os.path.basename(audio_file))[1]
    if extension == '.mp3':
        mp3 = MP3(audio_file, ID3=ID3)
        print(list(dict(mp3).keys()))
        if not regex_list(dict(mp3).keys(), re.compile('[Aa][Pp][Ii][Cc].*')):
            artist = mp3['TPE1'][0]
            album = mp3['TALB'][0]
            cover_data = open(get_cover_art(artist, album, audio_file), mode='rb')
            apic = APIC()
            apic.encoding = 3
            apic.mime = 'image/jpg'
            apic.type = PictureType.COVER_FRONT
            apic.desc = u'Cover'
            apic.data = cover_data.read()
            cover_data.close()
            print('Adding cover art', cover_data.name, '->', audio_file)
            mp3['APIC'] = apic
            mp3.save()
        else:
            print(audio_file, 'already has cover artwork.')
    elif extension == '.m4a' or extension is '.aac':
        m4a = MP4(audio_file)
        print(list(dict(m4a).keys()))
        if 'covr' not in m4a:
            artist = m4a['\xa9ART'][0]
            album = m4a['\xa9alb'][0]
            cover_data = open(get_cover_art(artist, album, audio_file), mode='rb')
            covr = MP4Cover()
            covr.imageformat = AtomDataType.JPEG
            covr.data = cover_data.read()
            cover_data.close()
            print('Adding cover art', cover_data.name, '->', audio_file)
            m4a['covr'] = [covr]
            m4a.save()
        else:
            print(audio_file, 'already has cover artwork.')
    elif extension == '.flac':
        flac = FLAC(audio_file)
        print(list(dict(flac).keys()))
        if not flac.pictures:
            artist = flac['artist'][0]
            album = flac['album'][0]
            cover_data = open(get_cover_art(artist, album, audio_file), mode='rb')
            picture = Picture()
            picture.type = 3
            picture.mime = 'image/jpg'
            picture.desc = u'Cover'
            picture.data = cover_data.read()
            cover_data.close()
            print('Adding cover artwork', cover_data.name, '->', audio_file)
            flac.add_picture(picture)
            flac.save()
        else:
            print(audio_file, 'already has cover artwork.')
    move_or_overwrite(audio_file, dest_audio, os.path.join(dest_audio, os.path.basename(audio_file)))
예제 #2
0
파일: tag.py 프로젝트: alexesprit/audiotool
 def __setattr__(self, attr, value):
     if attr in self.TAG_MAP:
         frame_id = self.TAG_MAP[attr]
         frame = self.audio.get(frame_id, None)
         if isinstance(value, Artwork):
             if not frame:
                 frame = APIC(encoding=3, type=3)
                 self.audio.add(frame)
             frame.data = value.data
             frame.mime = value.mime
         elif isinstance(value, str):
             if not frame:
                 frame = Frames[frame_id](encoding=3)
                 self.audio.add(frame)
             frame.text = [value]
         else:
             raise TagValueError(value)
     else:
         object.__setattr__(self, attr, value)
예제 #3
0
 def __setattr__(self, attr, value):
     if attr in self.TAG_MAP:
         frame_id = self.TAG_MAP[attr]
         frame = self.audio.get(frame_id, None)
         if isinstance(value, Artwork):
             if not frame:
                 frame = APIC(encoding=3, type=3)
                 self.audio.add(frame)
             frame.data = value.data
             frame.mime = value.mime
         elif isinstance(value, str):
             if not frame:
                 frame = Frames[frame_id](encoding=3)
                 self.audio.add(frame)
             frame.text = [value]
         else:
             raise TagValueError(value)
     else:
         object.__setattr__(self, attr, value)
예제 #4
0
def add_id3_art(path, url):
    try:
        art = requests.get(url)
        art.raise_for_status()

        mp3 = MP3(path, ID3=ID3)
        art_tag = APIC()
        art_tag.encoding = 3
        art_tag.type = 3
        art_tag.desc = u"Album Cover"
        if url.endswith('png'):
            art_tag.mime = u"image/png"
        else:
            art_tag.mime = u"image/jpeg"
        art_tag.data = art.content
        mp3.tags.add(art_tag)
        mp3.save()
    except requests.exceptions.RequestException:
        return
    except id3_error:
        return
예제 #5
0
    def _set_cover_data(self,
                        image: 'Image.Image',
                        data: bytes,
                        mime_type: str,
                        dry_run: bool = False):
        if self.tag_type == 'id3':
            current = self.tags_for_id('APIC')
            cover = APIC(mime=mime_type,
                         type=PictureType.COVER_FRONT,
                         data=data)  # noqa
            if self._log_cover_changes(current, cover, dry_run):
                self._f.tags.delall('APIC')
                self._f.tags[cover.HashKey] = cover
        elif self.tag_type == 'mp4':
            current = self._f.tags['covr']
            try:
                cover_fmt = MP4_MIME_FORMAT_MAP[mime_type]
            except KeyError as e:
                raise ValueError(
                    f'Invalid {mime_type=} for {self!r} - must be JPEG or PNG for MP4 cover images'
                ) from e
            cover = MP4Cover(data, cover_fmt)
            if self._log_cover_changes(current, cover, dry_run):
                self._f.tags['covr'] = [cover]
        elif self.tag_type == 'vorbis':
            current = self._f.pictures
            cover = Picture()
            cover.type = PictureType.COVER_FRONT  # noqa
            cover.mime = mime_type
            cover.width, cover.height = image.size
            cover.depth = 1 if image.mode == '1' else 32 if image.mode in (
                'I', 'F') else 8 * len(image.getbands())
            cover.data = data
            if self._log_cover_changes(current, cover, dry_run):
                self._f.clear_pictures()
                self._f.add_picture(cover)

        if not dry_run:
            self.save()
예제 #6
0
파일: audio.py 프로젝트: Python3pkg/PenPen
def addCoverArt(filename, config):
    """Add cover art."""
    logger.info("Adding the Cover Image...")

    # Check that the file exists
    imageFilepath = config['episodeImageFilepath']

    if not os.path.isfile(imageFilepath):
        logger.fatal("\'" + imageFilepath + "\' does not exist.")
        exit(1)

    # Initialize the tag
    imageTag = APIC()

    # Determine the file type
    if fileUtils.extValid(imageFilepath.lower(), '.png'):
        imageTag.mime = 'image/png'
    elif fileUtils.extValid(imageFilepath.lower(), '.jpg'):
        imageTag.mime = 'image/jpeg'
    else:
        logger.fatal("Cover image must be a PNG or JPG.")
        exit(1)

    # Set the image tags
    imageTag.encoding = 3  # 3 is for utf-8
    imageTag.type = 3  # 3 is for cover image
    imageTag.desc = u'Cover'

    with open(imageFilepath, 'rb') as f:
        imageTag.data = f.read()

    # Add the tag using ID3
    try:
        mp3 = MP3(filename, ID3=ID3)
        mp3.tags.add(imageTag)
        mp3.save()
    except:
        raise
예제 #7
0
파일: audio.py 프로젝트: ryanmeasel/PenPen
def addCoverArt(filename, config):
    """Add cover art."""
    logger.info("Adding the Cover Image...")

    # Check that the file exists
    imageFilepath = config['episodeImageFilepath']

    if not os.path.isfile(imageFilepath):
        logger.fatal("\'" + imageFilepath + "\' does not exist.")
        exit(1)

    # Initialize the tag
    imageTag = APIC()

    # Determine the file type
    if fileUtils.extValid(imageFilepath.lower(), '.png'):
        imageTag.mime = 'image/png'
    elif fileUtils.extValid(imageFilepath.lower(), '.jpg'):
        imageTag.mime = 'image/jpeg'
    else:
        logger.fatal("Cover image must be a PNG or JPG.")
        exit(1)

    # Set the image tags
    imageTag.encoding = 3  # 3 is for utf-8
    imageTag.type = 3      # 3 is for cover image
    imageTag.desc = u'Cover'

    with open(imageFilepath, 'rb') as f:
        imageTag.data = f.read()

    # Add the tag using ID3
    try:
        mp3 = MP3(filename, ID3=ID3)
        mp3.tags.add(imageTag)
        mp3.save()
    except:
        raise