Ejemplo n.º 1
0
 def __init__(self, audio, options, informalTagDict, browser):
     for tag in options["Selected Tags (L)"]:
         if tag in informalTagDict:
             setattr(self, tag.lower(), str(audio[informalTagDict[tag]][0]))
     self.imageSelection = "THUMB"
     if browser != '': self.browser = browser
     else: self.browser = 'NA'
     self.stop = False
     if "metadata_block_picture" in audio and options[
             'Stop Search After Conditions (B)'].get():
         imageFrame = audio["metadata_block_picture"]
         if imageFrame[0] != '':
             data = base64.b64decode(imageFrame[0])
             image = Picture(data)
             stream = BytesIO(image.data)
             image = Image.open(stream).convert("RGBA")
             width, height = image.size
             if width >= int(
                     options[
                         "Stop Search After Finding Image of Resolution (S)"]
                     .get().split('x')
                 [0]) and height >= int(options[
                     "Stop Search After Finding Image of Resolution (S)"].
                                        get().split('x')[1]):
                 self.stop = True
             stream.close()
Ejemplo n.º 2
0
 def testEqualPictures(self):
     p = Picture()
     self.assertTrue(self.comp.picture_equal())
     self.a.add_picture(p)
     self.assertFalse(self.comp.picture_equal())
     self.b.add_picture(p)
     self.assertTrue(self.comp.picture_equal())
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()
Ejemplo n.º 4
0
 def testCommonPictures(self):
     p = Picture()
     self.a.add_picture(p)
     self.assertEquals(self.comp.common_pictures(), [])
     self.b.add_picture(p)
     self.assertEquals(self.comp.common_pictures(), [p])
     self.assertTrue(self.comp.picture_equal())
Ejemplo n.º 5
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
Ejemplo n.º 6
0
    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
Ejemplo n.º 7
0
    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
Ejemplo n.º 8
0
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
Ejemplo n.º 9
0
 def write_tags(self, song, data):
     try:
         tag = mutagen.File(song, easy=True)
         tag.add_tags()
     except mutagen.flac.FLACVorbisError:
         tag = FLAC(song)
         tag.delete()
         images = Picture()
         images.type = 3
         images.data = data['image']
         tag.add_picture(images)
     except mutagen.id3._util.error:
         pass
     tag['artist'] = data['artist']
     tag['title'] = data['music']
     tag['date'] = data['year']
     tag['album'] = data['album']
     tag['tracknumber'] = data['tracknum']
     tag['discnumber'] = data['discnum']
     tag['genre'] = " & ".join(data['genre'])
     tag['albumartist'] = data['ar_album']
     tag.save()
     try:
         audio = ID3(song)
         audio['APIC'] = APIC(encoding=3,
                              mime="image/jpeg",
                              type=3,
                              desc=u"Cover",
                              data=data['image'])
         audio.save()
     except mutagen.id3._util.ID3NoHeaderError:
         pass
Ejemplo n.º 10
0
    def get_images(self):
        try:
            audio = self.MutagenType(self["~filename"])
        except Exception:
            return []

        # metadata_block_picture
        images = []
        for data in audio.get("metadata_block_picture", []):
            try:
                cover = Picture(base64.b64decode(data))
            except (TypeError, FLACError):
                continue

            f = get_temp_cover_file(cover.data)
            images.append(
                EmbeddedImage(f, cover.mime, cover.width, cover.height,
                              cover.depth, cover.type))

        # coverart + coverartmime
        cover = audio.get("coverart")
        try:
            cover = cover and base64.b64decode(cover[0])
        except TypeError:
            cover = None

        if cover:
            mime = audio.get("coverartmime")
            mime = (mime and mime[0]) or "image/"
            f = get_temp_cover_file(cover)
            images.append(EmbeddedImage(f, mime))

        images.sort(key=lambda c: c.sort_key)

        return images
Ejemplo n.º 11
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)
Ejemplo n.º 12
0
 def test_largest_valid(self):
     f = FLAC(self.filename)
     pic = Picture()
     pic.data = b"\x00" * (2**24 - 1 - 32)
     self.assertEqual(len(pic.write()), 2**24 - 1)
     f.add_picture(pic)
     f.save()
Ejemplo n.º 13
0
 def add_flac_cover(self, audio, albumart, desc='Album cover', file_type=3):
     image = Picture()
     image.type = file_type
     image.desc = desc
     with open(albumart, 'rb') as f:
         image.data = f.read()
     audio.add_picture(image)
Ejemplo n.º 14
0
    def test_get_images(self):
        # coverart + coverartmime
        data = _get_jpeg()
        song = self.MutagenType(self.filename)
        song["coverart"] = base64.b64encode(data).decode("ascii")
        song["coverartmime"] = u"image/jpeg"
        song.save()

        song = self.QLType(self.filename)
        self.assertEqual(len(song.get_images()), 1)
        self.assertEqual(song.get_images()[0].mime_type, "image/jpeg")

        # metadata_block_picture
        pic = Picture()
        pic.data = _get_jpeg()
        pic.type = APICType.COVER_FRONT
        b64pic_cover = base64.b64encode(pic.write()).decode("ascii")

        song = self.MutagenType(self.filename)
        song["metadata_block_picture"] = [b64pic_cover]
        song.save()

        song = self.QLType(self.filename)
        self.assertEqual(len(song.get_images()), 2)
        self.assertEqual(song.get_images()[0].type, APICType.COVER_FRONT)
Ejemplo n.º 15
0
 def test_add_picture(self):
     f = FLAC(self.NEW)
     c = len(f.pictures)
     f.add_picture(Picture())
     f.save()
     f = FLAC(self.NEW)
     self.failUnlessEqual(len(f.pictures), c + 1)
    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()
Ejemplo n.º 17
0
    def loadFrontCover(self):
        if self.debug: logging.debug("Suche OGG-Cover... %s" % (self.filename))
        diaMode = self.guiPlayer.slide_mode
        cover = None

        coverdesc = []
        covertype = []

        for frame in self.audio.keys():
            for tag in self.audio[frame]:
                if frame.lower() == "coverarttype":
                    if self.debug: logging.debug("Tag %s" % (frame))
                    covertype.append(tag)
                elif frame.lower() == "coverartdescription":
                    if self.debug: logging.debug("Tag %s" % (frame))
                    coverdesc.append(tag)

        for frame in self.audio.keys():
            if frame.lower() == "metadata_block_picture":
                pictures = []
                try:
                    pictures.append(
                        Picture(base64.b64decode(self.audio[frame])))
                except TypeError:
                    if self.debug: logging.debug("Fehler beim Bild.")

                for pic in pictures:
                    if pic.type == 3:
                        cover = self.getTempPic(pic.data)
                        break

            elif frame.lower() == "coverart":
                pictures = []
                for index, p in enumerate(self.audio[frame]):
                    coverdesc.append("unknown")
                    covertype.append(0)
                    coverTemp = self.audio[frame]
                    try:
                        coverTemp = coverTemp and base64.b64decode(
                            coverTemp[index])
                        if self.debug:
                            logging.debug(
                                "Cover # %s Type %s Desc: %s" %
                                (index, covertype[index], coverdesc[index]))
                        if int(covertype[index]) == 3:
                            cover = self.getTempPic(coverTemp)
                            break
                    except TypeError:
                        if self.debug:
                            logging.debug("Fehler bei Bild %s" % (index))

        if cover:
            if self.debug: logging.debug("... gefunden! ... ")
            self.cover = pygame.image.load(cover)
        else:
            if self.debug: logging.warning("... NICHT gefunden! ... ")
            self.cover = pygame.image.load(self.LEERCD)

        return
Ejemplo n.º 18
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
Ejemplo n.º 19
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')
Ejemplo n.º 20
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)
Ejemplo n.º 21
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)
Ejemplo n.º 22
0
def get_cover_art(ogg: OggVorbis) -> Image:
    "Read out cover art as a Pillow Image."
    ascii_bytes = ogg.tags["METADATA_BLOCK_PICTURE"][0]
    base64_bytes = ascii_bytes.encode("utf-8")
    decoded_bytes = base64.b64decode(base64_bytes)
    pic = Picture(data=decoded_bytes)
    byte_stream = io.BytesIO(pic.data)
    return Image.open(byte_stream)
Ejemplo n.º 23
0
def write_tags(song, data):
    try:
        tag = FLAC(song)
        tag.delete()
        images = Picture()
        images.type = 3
        images.data = data["image"]
        tag.clear_pictures()
        tag.add_picture(images)
        tag["lyrics"] = data["lyric"]
    except FLACNoHeaderError:
        try:
            tag = File(song, easy=True)
            tag.delete()
        except:
            if isfile(song):
                remove(song)

            raise exceptions.TrackNotFound("")
    except NOTVALIDSONG:
        raise exceptions.TrackNotFound("")

    tag["artist"] = data["artist"]
    tag["title"] = data["music"]
    tag["date"] = data["year"]
    tag["album"] = data["album"]
    tag["tracknumber"] = data["tracknum"]
    tag["discnumber"] = data["discnum"]
    tag["genre"] = data["genre"]
    tag["albumartist"] = data["ar_album"]
    tag["author"] = data["author"]
    tag["composer"] = data["composer"]
    tag["copyright"] = data["copyright"]
    tag["bpm"] = data["bpm"]
    tag["length"] = data["duration"]
    tag["organization"] = data["label"]
    tag["isrc"] = data["isrc"]
    tag["lyricist"] = data["lyricist"]
    tag.save()

    try:
        audio = ID3(song)

        audio.add(
            APIC(
                encoding=3,
                mime="image/jpeg",
                type=3,
                desc=u"Cover",
                data=data["image"],
            ))

        audio.add(
            USLT(encoding=3, lang=u"eng", desc=u"desc", text=data["lyric"]))

        audio.save()
    except ID3NoHeaderError:
        pass
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')
Ejemplo n.º 25
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)
Ejemplo n.º 26
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)

        """
Ejemplo n.º 27
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()
Ejemplo n.º 28
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()
Ejemplo n.º 29
0
 def _get_tag(self, raw, tag):
     value = CaseInsensitveBaseFormat._get_tag(self, raw, tag)
     if value and tag == 'metadata_block_picture':
         new_value = []
         for v in value:
             picture = Picture(base64.b64decode(v))
             new_value.append(CoverImage(type=picture.type, desc=picture.desc, mime=picture.mime, data=picture.data))
         value = new_value
     return value
Ejemplo n.º 30
0
Archivo: Qo-DL.py Proyecto: 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()