示例#1
0
文件: xiph.py 项目: yaoml/quodlibet
    def set_image(self, image):
        """Replaces all embedded images by the passed image"""

        with translate_errors():
            tag = FLAC(self["~filename"])

        try:
            data = image.read()
        except EnvironmentError as e:
            raise AudioFileError(e)

        pic = Picture()
        pic.data = data
        pic.type = APICType.COVER_FRONT
        pic.mime = image.mime_type
        pic.width = image.width
        pic.height = image.height
        pic.depth = image.color_depth

        tag.add_picture(pic)

        with translate_errors():
            tag.save()

        # clear vcomment tags
        super(FLACFile, self).clear_images()

        self.has_images = True
示例#2
0
文件: xiph.py 项目: zsau/quodlibet
    def set_image(self, image):
        """Replaces all embedded images by the passed image"""

        with translate_errors():
            tag = FLAC(self["~filename"])

        try:
            data = image.read()
        except EnvironmentError as e:
            raise AudioFileError(e)

        pic = Picture()
        pic.data = data
        pic.type = APICType.COVER_FRONT
        pic.mime = image.mime_type
        pic.width = image.width
        pic.height = image.height
        pic.depth = image.color_depth

        tag.add_picture(pic)

        with translate_errors():
            tag.save()

        # clear vcomment tags
        super(FLACFile, self).clear_images()

        self.has_images = True
def download_and_fix_ogg(ogg, audio_metadata, cover_art_file):
    global DRY_RUN
    if DRY_RUN:
        print "This is a dry run. So pretending to download the ogg..."
        return "/tmp/ogg"
    print "Now downloading the ogg in order to set the metadata in it..."
    if not LIVE and len(sys.argv) >= 6 and os.path.exists(sys.argv[5]):
        ogg_local_fn = sys.argv[5]
        print "(using presupplied file %s)" % ogg_local_fn
    else:
        f, metadata = client.get_file_and_metadata(ogg)
        ogg_local_fn = fetch_file(f, metadata)
    print "Successfully downloaded (to %s): now editing metadata..." % ogg_local_fn
    audio = OggVorbis(ogg_local_fn)
    for k in audio_metadata.keys():
        audio[k] = audio_metadata[k]
    # add cover art
    im=Image.open(cover_art_file)
    w,h=im.size
    p=Picture()
    imdata=open(cover_art_file,'rb').read()
    p.data=imdata
    p.type=3
    p.desc=''
    p.mime='image/jpeg';
    p.width=w; p.height=h
    p.depth=24
    dt=p.write(); 
    enc=base64.b64encode(dt).decode('ascii');
    audio['metadata_block_picture']=[enc];
    audio.save()
    print "Successfully updated metadata."
    return ogg_local_fn
def saveImage(track, audio, window):
    # store image data, width, and height from downloaded image into imageSelection field
    if track.imageSelection != "THUMB":
        # first clear all images from audio file
        audio.clear_pictures()
        # file image import will be used as a thumbnail in various windows
        fileImageImport = Image.open(
            resource_path('Temp/' + str(track.imageSelection) + '.jpg'))
        width, height = fileImageImport.size
        fileImageImport = fileImageImport.resize((200, 200), Image.ANTIALIAS)
        # image will be saved directly to the file
        image = Picture()
        with open(resource_path('Temp/' + str(track.imageSelection) + '.jpg'),
                  'rb') as f:
            image.data = f.read()
        image.type = id3.PictureType.COVER_FRONT
        image.mime = u"image/jpeg"
        audio.add_picture(image)
        audio.save()
        track.imageSelection = [fileImageImport, width, height]
    # check if current track has artwork image
    else:
        if len(audio.pictures) > 0:
            stream = BytesIO(audio.pictures[0].data)
            image = Image.open(stream).convert("RGBA")
            width, height = image.size
            image = image.resize((200, 200), Image.ANTIALIAS)
            track.imageSelection = [image, width, height]
        else:
            image = Image.open(resource_path('Thumbnail.png'))
            image = image.resize((200, 200), Image.ANTIALIAS)
            track.imageSelection = [image, '', '']
    window.destroy()
示例#5
0
文件: xiph.py 项目: zsau/quodlibet
    def set_image(self, image):
        """Replaces all embedded images by the passed image"""

        with translate_errors():
            audio = self.MutagenType(self["~filename"])

        try:
            data = image.read()
        except EnvironmentError as e:
            raise AudioFileError(e)

        pic = Picture()
        pic.data = data
        pic.type = APICType.COVER_FRONT
        pic.mime = image.mime_type
        pic.width = image.width
        pic.height = image.height
        pic.depth = image.color_depth

        audio.pop("coverart", None)
        audio.pop("coverartmime", None)
        audio["metadata_block_picture"] = base64.b64encode(
            pic.write()).decode("ascii")

        with translate_errors():
            audio.save()

        self.has_images = True
    def as_flac(self, path, metadata, cached_albumart=None):
        logger.debug('Writing FLAC metadata to "{path}".'.format(path=path))
        # For supported flac tags:
        # https://github.com/quodlibet/mutagen/blob/master/mutagen/mp4/__init__.py
        # Look for the class named `MP4Tags` in the linked source file
        audiofile = FLAC(path)
        self._embed_basic_metadata(audiofile, metadata, "flac")
        if metadata["year"]:
            audiofile["year"] = metadata["year"]
        provider = metadata["provider"]
        audiofile["comment"] = metadata["external_urls"][provider]
        if metadata["lyrics"]:
            audiofile["lyrics"] = metadata["lyrics"]

        image = Picture()
        image.type = 3
        image.desc = "Cover"
        image.mime = "image/jpeg"
        if cached_albumart is None:
            cached_albumart = urllib.request.urlopen(
                metadata["album"]["images"][0]["url"]
            ).read()
            albumart.close()
        image.data = cached_albumart
        audiofile.add_picture(image)

        audiofile.save()
示例#7
0
 def _add_picture(self, mime, type_, desc, data):
     picture = Picture()
     picture.data = data
     picture.mime = mime
     picture.type = type_
     picture.desc = desc
     self._flac.add_picture(picture)
示例#8
0
 def set_art(self, art_file):
     art_tag = mutagen.File(self.path, None, False)
     if type(art_tag) is mutagen.mp3.MP3:
         with open(art_file, 'rb') as f:
             image = f.read()
         art_tag.tags.delall('APIC')
         art_tag.tags.add(APIC(
             encoding=3,  # 3 is for utf-8
             mime='image/jpg',  # image/jpeg or image/png
             type=3,  # 3 is for the cover image
             desc=u'Cover',
             data=image
             ))
         art_tag.save()
         print 'Wrote embedded MP3 art.'
     if type(art_tag) is mutagen.flac.FLAC:
         image = Picture()
         image.type = 3
         image.mime = 'image/jpg'
         image.desc = 'front cover'
         with open(art_file, 'rb') as f:
             image.data = f.read()
         art_tag.clear_pictures()
         art_tag.add_picture(image)
         art_tag.save()
         print 'Wrote embedded FLAC art'
示例#9
0
文件: xiph.py 项目: yaoml/quodlibet
    def set_image(self, image):
        """Replaces all embedded images by the passed image"""

        with translate_errors():
            audio = self.MutagenType(self["~filename"])

        try:
            data = image.read()
        except EnvironmentError as e:
            raise AudioFileError(e)

        pic = Picture()
        pic.data = data
        pic.type = APICType.COVER_FRONT
        pic.mime = image.mime_type
        pic.width = image.width
        pic.height = image.height
        pic.depth = image.color_depth

        audio.pop("coverart", None)
        audio.pop("coverartmime", None)
        audio["metadata_block_picture"] = base64.b64encode(
            pic.write()).decode("ascii")

        with translate_errors():
            audio.save()

        self.has_images = True
示例#10
0
 def _addCoverToFile(self, album):
     if self.fileType == 'FLAC':
         if not self.hasCover or (
                 self.audioTag.pictures[0].height != 1000 and self.audioTag.pictures[0].width != 1000):
             if self.hasCover:
                 self.audioTag.clear_pictures()
             # Build the file path by concatenating folder in the file path
             path = ''
             for folder in self.pathList:
                 path += '{}/'.format(folder)
             path += album.coverName
             with open(path, "rb") as img:
                 data = img.read()
             # Open physical image
             im = PIL.Image.open(path)
             width, height = im.size
             # Create picture and set its internals
             picture = Picture()
             picture.data = data
             picture.type = 3  # COVER_FRONT
             picture.desc = path.rsplit('/', 1)[-1]  # Add picture name as a description
             picture.mime = mimetypes.guess_type(path)[0]
             picture.width = width
             picture.height = height
             picture.depth = mode_to_bpp[im.mode]
             # Save into file's audio tag
             self.audioTag.add_picture(picture)
             self.audioTag.save()
     else:
         # TODO for APIC frame
         pass
示例#11
0
def set_OPUS_data(song, song_path):
    """
    Set the data into an OPUS container according to the
    passed data.
    """
    COVER_ADDED = False

    try:
        SONG_PATH = os.path.join(defaults.DEFAULT.SONG_TEMP_DIR,
                                 song_path)
        mutagen_file = File(SONG_PATH)

        # Try adding the tags container
        try:
            mutagen_file.add_tags()
        except Exception:
            # If exception is thrown, the tags already exist
            pass

        # Clear out the tags from the file
        mutagen_file.clear()

        # Try adding the cover
        if dwCover(song):
            imagedata = open(defaults.DEFAULT.COVER_IMG, 'rb').read()
            picture = Picture()
            picture.data = imagedata
            picture.type = PictureType.COVER_FRONT
            picture.mime = "image/jpeg"
            encoded_data = b64encode(picture.write())
            mutagen_file["metadata_block_picture"] = encoded_data.decode(
                                                     "ascii")

            # Remove the image
            os.remove(defaults.DEFAULT.COVER_IMG)
            COVER_ADDED = True

        # Add the tags now
        # Refer to https://www.programcreek.com/python/example/63675/mutagen.File
        # for more information on it
        mutagen_file["Title"] = song.track_name
        mutagen_file["Album"] = song.collection_name
        mutagen_file["Artist"] = song.artist_name
        mutagen_file["Date"] = song.release_date
        mutagen_file["Genre"] = song.primary_genre_name

        mutagen_file.save()

        defaults.DEFAULT.SONG_NAME_TO_SAVE = song.track_name + '.opus'

        # Rename the downloaded file
        os.rename(SONG_PATH, os.path.join(
            defaults.DEFAULT.SONG_TEMP_DIR,
            defaults.DEFAULT.SONG_NAME_TO_SAVE
        ))

        return COVER_ADDED
    except Exception as e:
        return e
示例#12
0
 def embed_art(self, art_path):
     pic = Picture()
     with open(art_path, "rb") as f:
         pic.data = f.read()
     pic.type = 3  # front cover
     pic.mime = MetaAudio.get_mime_type(art_path)
     pic.desc = 'front cover'
     self.audio.add_picture(pic)
示例#13
0
 def embed_art(self, art_path):
     pic = Picture()
     with open(art_path, "rb") as f:
         pic.data = f.read()
     pic.type = 3  # front cover
     pic.mime = MetaAudio.get_mime_type(art_path)
     pic.desc = 'front cover'
     self.audio[ART_TAG] = base64.b64encode(pic.write()).decode('utf8')
示例#14
0
 def picture(self, url):
     from mutagen.flac import Picture
     image = Picture()
     image.type = 3
     image.mime = 'image/jpeg'
     image.desc = 'front cover'
     image.data = get(url).content
     self.audio.add_picture(image)
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)))
示例#16
0
文件: Qo-DL.py 项目: 19h/Qo-DL
def add_flac_cover(filename, albumart):
    audio = File(str(filename))
    image = Picture()
    image.type = 3
    image.mime = "image/jpeg"
    with open(albumart, 'rb') as f:
        image.data = f.read()
        audio.add_picture(image)
        audio.save()
示例#17
0
    async def add(self):
        loop = asyncio.get_event_loop()
        await loop.run_in_executor(
            None, super().__init__, f"{self.trackInfo['trackId']}.ogg"
        )
        async with httpx.AsyncClient() as client:
            albumArtResponse = await client.get(self.trackInfo["albumArtHigh"])
        picture = Picture()
        picture.data = albumArtResponse.content
        """
        Initially Vorbis comments didn't contain album arts, now they can keep album arts according to FLAC's specifications, thus using Picture class from flac.
        mutagen example uses picture.type = 17 here: https://mutagen.readthedocs.io/en/latest/user/vcomment.html.
        Keeping it's value as 17 makes Android's MediaMetadataRetriever to not detect the album art.
        What on earth is "A bright coloured fish" ?
        Reference: https://xiph.org/flac/format.html#metadata_block_picture.
        """
        picture.type = 3
        picture.desc = "Cover (front)"
        picture.mime = "image/jpeg"
        picture.width = 544
        picture.height = 544
        encoded_data = base64.b64encode(picture.write())
        vcomment_value = encoded_data.decode("ascii")
        """
        Sets album art.
        """
        self["metadata_block_picture"] = [vcomment_value]
        """
        In Vorbis comments, a key e.g. "artists" can have more than one value.
        In mutagen implementation, that's why we give values in a list.
        Reference: https://gitlab.gnome.org/GNOME/rhythmbox/-/issues/16
        """
        self["title"] = [self.trackInfo["trackName"]]
        self["album"] = [self.trackInfo["albumName"]]
        """
        This is where we can simply provide simply a list of artists, as written above (for having mutiple value for the same key).     
        But, by that MediaMetadataRetriever is just shows first artist :-(. So, I'm just joining all artists with "/" separator. (Though, this is incorrect according to official reference).
        """
        self["artist"] = ["/".join(self.trackInfo["trackArtistNames"])]
        """
        No reference of this comment at http://age.hobba.nl/audio/mirroredpages/ogg-tagging.html, still using because a mutagen example uses it. Thus, unable to read.
        """
        self["albumartist"] = [self.trackInfo["albumArtistName"]]
        """
        This needs a fix. Vorbis comment keeps date instead of year & MediaMetadataRetriever is unable to read this.
        Fix if you get to know something...
        """
        self["date"] = [str(self.trackInfo["year"])]
        self["tracknumber"] = [f"{self.trackInfo['trackNumber']}/{self.trackInfo['albumLength']}"]
        """
        Again, no official reference of this one at http://age.hobba.nl/audio/mirroredpages/ogg-tagging.html. Thus, unable to read.
        """
        self["tracktotal"] = [str(self.trackInfo["albumLength"])]
        loop = asyncio.get_event_loop()
        await loop.run_in_executor(None, self.save)

        """
示例#18
0
def download_flac(track: tidalapi.models.Track, file_path, album=None):
    if album is None:
        album = track.album
    url = session.get_media_url(track_id=track.id)

    r = requests.get(url, stream=True)
    r.raw.decode_content = True
    data = BytesIO()
    shutil.copyfileobj(r.raw, data)
    data.seek(0)
    audio = FLAC(data)

    # general metatags
    audio['artist'] = track.artist.name
    audio[
        'title'] = f'{track.name}{f" ({track.version})" if track.version else ""}'

    # album related metatags
    audio['albumartist'] = album.artist.name
    audio[
        'album'] = f'{album.name}{f" ({album.version})" if album.version else ""}'
    audio['date'] = str(album.year)

    # track/disc position metatags
    audio['discnumber'] = str(track.volumeNumber)
    audio['disctotal'] = str(album.numberOfVolumes)
    audio['tracknumber'] = str(track.trackNumber)
    audio['tracktotal'] = str(album.numberOfTracks)

    # Tidal sometimes returns null for track copyright
    if hasattr(track, 'copyright') and track.copyright:
        audio['copyright'] = track.copyright
    elif hasattr(album, 'copyright') and album.copyright:
        audio['copyright'] = album.copyright

    # identifiers for later use in own music libraries
    if hasattr(track, 'isrc') and track.isrc:
        audio['isrc'] = track.isrc
    if hasattr(album, 'upc') and album.upc:
        audio['upc'] = album.upc

    pic = Picture()
    pic.type = id3.PictureType.COVER_FRONT
    pic.width = 640
    pic.height = 640
    pic.mime = 'image/jpeg'
    r = requests.get(track.album.image, stream=True)
    r.raw.decode_content = True
    pic.data = r.raw.read()

    audio.add_picture(pic)

    data.seek(0)
    audio.save(data)
    with open(file_path, "wb") as f:
        data.seek(0)
        shutil.copyfileobj(data, f)
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')
示例#20
0
 def ogg():
     song = OggVorbis(file)
     write_keys(song)
     if exists(cover_img):
         pic = Picture()
         pic.data = open(cover_img, 'rb').read()
         pic.mime = 'image/jpeg'
         song["metadata_block_picture"] = [base64.b64encode(pic.write()).decode('ascii')]
         song.save()
示例#21
0
 def flac():
     song = FLAC(file)
     write_keys(song)
     if exists(cover_img):
         pic = Picture()
         pic.data = open(cover_img, 'rb').read()
         pic.mime = 'image/jpeg'
         song.add_picture(pic)
         song.save()
示例#22
0
 def _picture_f2m(flackup_picture):
     """Create a Mutagen Picture from a Flackup Picture."""
     picture = MutagenPicture()
     picture.type = flackup_picture.type
     picture.mime = flackup_picture.mime
     picture.width = flackup_picture.width
     picture.height = flackup_picture.height
     picture.depth = flackup_picture.depth
     picture.data = flackup_picture.data
     return picture
示例#23
0
    def embed_cover_art(self, audio_file, cover_file):
        """Embeds cover art into an audio file.

		Arguments:
			audio_file (str): The path to the audio file to embed the artwork in.
			cover_file (str): The path to the artwork file to embed.
		"""
        if path.isfile(audio_file) and path.isfile(cover_file):
            mimetype = "image/png" if cover_file.endswith("png") else "image/jpeg"
            artwork = open(cover_file, "rb").read()
            desc = u"Cover Art"

            # Determine which filetype we're handling
            if audio_file.endswith("m4a"):
                audio = MP4(audio_file)

                covr = []
                if cover_file.endswith("png"):
                    covr.append(MP4Cover(artwork, MP4Cover.FORMAT_PNG))
                else:
                    covr.append(MP4Cover(artwork, MP4Cover.FORMAT_JPEG))

                audio.tags["covr"] = covr
            elif audio_file.endswith("mp3"):
                audio = MP3(audio_file, ID3=ID3)

                # Add ID3 tags if they don't exist
                try:
                    audio.add_tags()
                except error:
                    pass

                audio.tags.add(
                    APIC(
                        encoding=3,  # 3 is UTF-8
                        mime=mimetype,
                        type=3,  # 3 is for cover artwork
                        desc=desc,
                        data=artwork,
                    )
                )
            elif audio_file.endswith("flac"):
                audio = FLAC(audio_file)

                image = Picture()
                image.type = 3  # 3 is for cover artwork
                image.mime = mimetype
                image.desc = desc
                image.data = artwork

                audio.clear_pictures()  # Clear existing pictures
                audio.add_picture(image)

                # Save the audio file
        audio.save()
示例#24
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)
示例#25
0
def writeAlbumCover(songPath: str, coverPath: str, picData=None):
    """ 给音频文件写入封面
    Parameters
    ----------
    songPath: 音频文件路径\n
    coverPath: 封面图片路径\n
    picData: 封面图片二进制数据
    """
    id_card = File(songPath)
    # 读取封面数据
    if not picData:
        with open(coverPath, 'rb') as f:
            picData = f.read()
    # 获取音频数据和图片数据后缀名
    audioSuffix = id_card.mime[0].split('/')[-1]
    try:
        picSuffix = imghdr.what(None, picData)
    except:
        picSuffix = 'jpeg'
    mimeType = 'image/' + picSuffix
    # 开始写入封面
    if audioSuffix == 'mp3':
        keyName = 'APIC:'
        keyName_list = []
        # 获取可能已经存在的封面键名
        for key in id_card.tags.keys():
            if key.startswith('APIC'):
                keyName = key
                keyName_list.append(key)
        # 弹出所有旧标签才能写入新数据
        for key in keyName_list:
            id_card.pop(key)
        id_card[keyName] = APIC(encoding=0,
                                mime=mimeType,
                                type=3,
                                desc='',
                                data=picData)
    elif audioSuffix == 'flac':
        # 创建Picture实例
        picture = Picture()
        # 设置属性值
        picture.mime = mimeType
        picture.data = picData
        picture.type = 0
        # 清除原来的图片数据
        id_card.clear_pictures()
        # 添加图片
        id_card.add_picture(picture)
    elif audioSuffix == 'mp4':
        try:
            id_card['covr'][0] = picData
        except:
            id_card['covr'] = [picData]  # 没有键时需要创建一个
    id_card.save()
示例#26
0
文件: flac.py 项目: Oroggs/musiclib
def write_tags(f, meta, cov):
    audio = FLAC(f)
    for tag, value in meta.items():
        if value:
            audio[tag] = str(value)
    if cov:
        image = Picture()
        image.type = 3
        image.mime = "image/jpeg"
        image.data = cov
        audio.add_picture(image)
    audio.save()
示例#27
0
def add_flac_tags(path, tags, image, lyrics=None, image_mimetype='image/jpg'):
    tag = FLAC(path)
    pic = Picture()
    pic.data = image
    pic.type = 3
    pic.mime = image_mimetype
    tag.add_picture(pic)
    for key, val in tags.items():
        try:
            tag[key] = str(val)
        except Exception as e:
            print(e)
    tag.save()
示例#28
0
    def update_flac(self, path: str, track: beatport.Track):
        f = FLAC(path)

        if UpdatableTags.title in self.config.update_tags and self.config.overwrite:
            f['TITLE'] = track.title
        if UpdatableTags.artist in self.config.update_tags and self.config.overwrite:
            f['ARTIST'] = self.config.artist_separator.join(
                [a.name for a in track.artists])
        if UpdatableTags.album in self.config.update_tags and (
                self.config.overwrite or f.get('ALBUM') == None):
            f['ALBUM'] = track.album.name
        if UpdatableTags.label in self.config.update_tags and (
                self.config.overwrite or f.get('LABEL') == None):
            f['LABEL'] = track.label.name
        if UpdatableTags.bpm in self.config.update_tags and (
                self.config.overwrite or f.get('BPM') == None):
            f['BPM'] = str(track.bpm)
        if UpdatableTags.genre in self.config.update_tags and (
                self.config.overwrite or f.get('GENRE') == None):
            f['GENRE'] = ', '.join([g.name for g in track.genres])
        if UpdatableTags.date in self.config.update_tags and (
                self.config.overwrite or f.get('DATE') == None):
            f['DATE'] = track.release_date.strftime('%Y-%m-%d')
            #Year - part of date
        if UpdatableTags.key in self.config.update_tags and (
                self.config.overwrite or f.get('INITIALKEY') == None):
            f['INITIALKEY'] = track.id3key()
        if UpdatableTags.publishdate in self.config.update_tags and (
                self.config.overwrite or f.get('ORIGINALDATE') == None):
            f['ORIGINALDATE'] = str(track.publish_date.year)
        #Other tags
        if UpdatableTags.other in self.config.update_tags:
            f['WWWAUDIOFILE'] = track.url()
            f['WWWPUBLISHER'] = track.label.url('label')

        #Redownlaod cover
        if self.config.replace_art:
            try:
                url = track.art(self.config.art_resolution)
                r = requests.get(url)
                image = Picture()
                image.type = 3
                image.mime = 'image/jpeg'
                image.desc = 'Cover'
                image.data = r.content
                f.clear_pictures()
                f.add_picture(image)
            except Exception:
                logging.warning('Error downloading cover for file: ' + path)

        f.save()
示例#29
0
    def set_image(self, image):
        pic = Picture()
        pic.data = image.read()
        pic.type = COVER_FRONT
        pic.mime = image.mime_type
        pic.width = image.width
        pic.height = image.height
        # pic.depth = image.color_depth

        self.audio.add_picture(pic)
        with translate_errors():
            self.audio.save()
        # clear vcomment tags
        super().clear_images()
示例#30
0
    def get_cover_picture(self, cover):
        """ Returns mutage Picture class for the cover image
        Usefull for OGG and FLAC format

        Picture type = cover image
        see http://flac.sourceforge.net/documentation_tools_flac.html#encoding_options
        """
        f = file(cover)
        p = Picture()
        p.type = 3
        p.data = f.read()
        p.mime = mimetypes.guess_type(cover)[0]
        f.close()

        return p
示例#31
0
文件: flac.py 项目: exaile/exaile
    def _set_tag(self, raw, tag, value):
        if tag == '__cover':
            raw.clear_pictures()
            for v in value:
                picture = Picture()
                picture.type = v.type
                picture.desc = v.desc
                picture.mime = v.mime
                picture.data = v.data
                raw.add_picture(picture)
            return

        # flac has text based attributes, so convert everything to unicode
        value = [xl.unicode.to_unicode(v) for v in value]
        CaseInsensitveBaseFormat._set_tag(self, raw, tag, value)
示例#32
0
    def set_image(self, image):
        """Replaces all embedded images by the passed image"""

        with image:
            pic = Picture()
            pic.data = image.read()
            pic.type = COVER_FRONT
            pic.mime = image.mime_type
            pic.width = image.width
            pic.height = image.height

            self.audio.pop("coverart", None)
            self.audio.pop("coverartmime", None)
            self.audio["metadata_block_picture"] = base64.b64encode(
                pic.write()).decode("ascii")
示例#33
0
文件: ogg.py 项目: exaile/exaile
 def _set_tag(self, raw, tag, value):
     if tag == 'metadata_block_picture':
         new_value = []
         for v in value:
             picture = Picture()
             picture.type = v.type
             picture.desc = v.desc
             picture.mime = v.mime
             picture.data = v.data
             new_value.append(base64.b64encode(picture.write()))
         value = new_value
     else:
         # vorbis has text based attributes, so convert everything to unicode
         value = [xl.unicode.to_unicode(v) for v in value]
     CaseInsensitveBaseFormat._set_tag(self, raw, tag, value)
示例#34
0
    def _set_tag(self, raw, tag, value):
        if tag == '__cover':
            raw.clear_pictures()
            for v in value:
                picture = Picture()
                picture.type = v.type
                picture.desc = v.desc
                picture.mime = v.mime
                picture.data = v.data
                raw.add_picture(picture)
            return

        # flac has text based attributes, so convert everything to unicode
        value = [xl.unicode.to_unicode(v) for v in value]
        CaseInsensitveBaseFormat._set_tag(self, raw, tag, value)
示例#35
0
def write_tags(pre_path, meta, cov_path):
	del meta['track_padded']
	audio = FLAC(pre_path)
	audio.delete()
	for k, v in meta.items():
		if v:
			audio[k] = str(v)
	if cov_path:
		image = Picture()
		with open(cov_path, 'rb') as f:
			image.data = f.read()
		image.type = 3
		image.mime = "image/jpeg"
		audio.add_picture(image)
	audio.save(pre_path)
示例#36
0
 def _set_tag(self, raw, tag, value):
     if tag == 'metadata_block_picture':
         new_value = []
         for v in value:
             picture = Picture()
             picture.type = v.type
             picture.desc = v.desc
             picture.mime = v.mime
             picture.data = v.data
             new_value.append(base64.b64encode(picture.write()))
         value = new_value
     else:
         # vorbis has text based attributes, so convert everything to unicode
         value = [xl.unicode.to_unicode(v) for v in value]
     CaseInsensitveBaseFormat._set_tag(self, raw, tag, value)
示例#37
0
 def __setattr__(self, attr, value):
     if attr in self.VALID_TAG_KEYS:
         if isinstance(value, Artwork):
             picture = Picture()
             picture.type = 3
             picture.mime = value.mime
             picture.data = value.data
             self.audio.clear_pictures()
             self.audio.add_picture(picture)
         elif isinstance(value, str):
             self.audio[attr] = [value]
         else:
             raise TagValueError(value)
     else:
         object.__setattr__(self, attr, value)
示例#38
0
 def __setattr__(self, attr, value):
     if attr in self.VALID_TAG_KEYS:
         if isinstance(value, Artwork):
             picture = Picture()
             picture.type = 3
             picture.mime = value.mime
             picture.data = value.data
             self.audio.clear_pictures()
             self.audio.add_picture(picture)
         elif isinstance(value, str):
             self.audio[attr] = [value]
         else:
             raise TagValueError(value)
     else:
         object.__setattr__(self, attr, value)
示例#39
0
    def get_cover_picture(self, cover):
        """ Returns mutagen Picture class for the cover image
        Usefull for OGG and FLAC format

        Picture type = cover image
        see http://flac.sourceforge.net/documentation_tools_flac.html#encoding_options
        """
        f = file(cover)
        p = Picture()
        p.type = 3
        p.data = f.read()
        p.mime = mimetypes.guess_type(cover)[0]
        f.close()

        return p
示例#40
0
文件: tag.py 项目: jacron/music_a
def tag_put_picture(album_id):
    pic = Picture()
    album = get_album(album_id)
    with open(album['Path'] + "/folder.jpg", "rb") as f:
        pic.data = f.read()
    if not pic.data:
        return 'No folder.jpg found'
    pic.type = id3.PictureType.COVER_FRONT
    pic.mime = u"image/jpeg"
    pic.width = 500
    pic.height = 500
    pic.depth = 16
    for p in tag_get_piece_paths(album_id):
        set_pic(p, pic)
    return 'success'
示例#41
0
 def __setattr__(self, attr, value):
     if attr in self.VALID_TAG_KEYS:
         if isinstance(value, Artwork):
             picture = Picture()
             picture.type = 3
             picture.mime = value.mime
             picture.data = value.data
             self.audio['metadata_block_picture'] = [
                 b64encode(picture.write()).decode('utf-8')
             ]
         elif isinstance(value, str):
             self.audio[attr] = [value]
         else:
             raise TagValueError(value)
     else:
         object.__setattr__(self, attr, value)
示例#42
0
def ogg_coverart(config):
    print("Adding " + config.coverart_mime +  " cover art to " + config.ogg_file)
    coverart = config.coverart
    imgdata = open(coverart,'rb').read()

    im = Image.open(coverart)
    w,h = im.size

    p = Picture()
    p.data = imgdata
    p.type = 3
    p.desc = 'Cover'
    p.mime = config.coverart_mime
    p.width = w
    p.height = h
    p.depth = 24
    dt=p.write()
    enc=base64.b64encode(dt).decode('ascii')

    audio = OggVorbis(config.ogg_file)
    audio['metadata_block_picture']=[enc]
    audio.save()
示例#43
0
    def set_image(self, image):
        """Replaces all embedded images by the passed image"""

        try:
            audio = self.MutagenType(self["~filename"])
            data = image.file.read()
        except EnvironmentError:
            return

        pic = Picture()
        pic.data = data
        pic.type = APICType.COVER_FRONT
        pic.mime = image.mime_type
        pic.width = image.width
        pic.height = image.height
        pic.depth = image.color_depth

        audio.pop("coverart", None)
        audio.pop("coverartmime", None)
        audio["metadata_block_picture"] = base64.b64encode(pic.write())
        audio.save()

        self.has_images = True