Exemplo n.º 1
0
    def test_repr(self):
        frame = APIC(encoding=0, mime=u"m", type=3, desc=u"d", data=b"\x42")
        if PY2:
            expected = (
                "APIC(encoding=<Encoding.LATIN1: 0>, mime=u'm', "
                "type=<PictureType.COVER_FRONT: 3>, desc=u'd', data='B')")
        else:
            expected = (
                "APIC(encoding=<Encoding.LATIN1: 0>, mime='m', "
                "type=<PictureType.COVER_FRONT: 3>, desc='d', data=b'B')")

        self.assertEqual(repr(frame), expected)
        new_frame = APIC()
        new_frame._readData(frame._writeData())
        self.assertEqual(repr(new_frame), expected)
Exemplo n.º 2
0
def add_albumart(albumart, song_title):
    '''
    Adds the album art to the song
    '''

    try:
        img = urlopen(albumart)  # Gets album art from url

    except Exception:
        log.log_error("* Could not add album art", indented=True)
        return None

    audio = EasyMP3(song_title, ID3=ID3)
    try:
        audio.add_tags()
    except _util.error:
        pass

    audio.tags.add(
        APIC(
            encoding=3,  # UTF-8
            mime='image/png',
            type=3,  # 3 is for album art
            desc='Cover',
            data=img.read()  # Reads and adds album art
        ))
    audio.save()
    log.log("> Added album art")
Exemplo n.º 3
0
def set_info(file, sformat, art='', alb='', img='', nam=''):
    if sformat == 'm4a':
        mu = File(file)
        if art:
            mu['©ART'] = art
        if alb:
            mu['©alb'] = alb
        if img:
            mu['covr'] = [MP4Cover(img)]
        if nam:
            mu['©nam'] = nam
        mu.save()
    elif sformat == 'mp3':
        audio = ID3(file)
        if img:
            #img:
            audio['APIC'] = APIC(encoding=3,
                                 mime='image/jpeg',
                                 sformat=3,
                                 desc=u'Cover',
                                 data=img)
        if nam:
            #title
            audio['TIT2'] = TIT2(encoding=3, text=[nam])
        if art:
            #art:
            audio['TPE1'] = TPE1(encoding=3, text=[art])
        if alb:
            #album:
            audio['TALB'] = TALB(encoding=3, text=[alb])
        audio.save()
Exemplo n.º 4
0
def write_tags(song, data):
    tag = EasyID3(song)
    tag.delete()
    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['bpm'] = data['bpm']
    tag['length'] = data['duration']
    tag['organization'] = data['label']
    tag['isrc'] = data['isrc']
    tag['replaygain_*_gain'] = data['gain']
    tag.save(v2_version=3)
    audio = ID3(song)

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

    audio.save()
Exemplo n.º 5
0
def edit_id3_tags(track, mp3_path, img_path):
    # Edit Artist/Title ID3 tags
    # http://stackoverflow.com/questions/18369188/python-add-id3-tags-to-mp3-file-that-has-no-tags
    logging.debug("Adding artist/title ID3 tags...")
    meta = mutagen.File(mp3_path, easy=True)
    meta["title"] = track.title
    meta["artist"] = track.artist
    meta["album"] = "SoundCloud"
    meta.save()

    # Embed description into lyrics field
    if track.description is not None:
        logging.debug("Writing description to lyrics field...")
        audio = ID3(mp3_path)
        audio.add(
            USLT(encoding=3, lang=u'eng', desc=u'desc',
                 text=track.description))
        audio.save()

    # Embed album art
    if track.artwork_url is not None:
        logging.debug("Adding album art...")
        audio = ID3(mp3_path)
        audio.add(
            APIC(
                encoding=3,  # 3 is for utf-8
                mime='image/jpeg',  # image/jpeg or image/png
                type=3,  # 3 is for the cover image
                desc='Cover',
                data=open(img_path, "rb").read()))
        audio.save()
Exemplo n.º 6
0
    def settingImage(self):

        pattern = r'(jpg)$|(png)$'

        if self.Image is None:
            return

        mp3 = MP3('./{}.mp3'.format(self.soundName), ID3=ID3)
        ext = re.search(pattern, self.ImageURL).group(1)

        if ext == 'jpg':
            ext = 'jpeg'

        try:
            mp3.add_tags()
        except error:
            pass

        mp3.tags.add(
            APIC(encoding=3,
                 mime='image/{}'.format(ext),
                 type=3,
                 desc='Cover',
                 data=self.Image))

        mp3.save()
Exemplo n.º 7
0
def add_metadata_to_song(file_path, songinfoDict):
    data = requests.get(songinfoDict['cover']).content
    try:
        audio = MP3(file_path, ID3=ID3)
    except HeaderNotFoundError:
        print("找不到歌曲文件!")
        return

    if audio.tags is None:
        print("没有ID3,尝试添加!")
        try:
            audio.add_tags()
            audio.save()
        except error as e:
            print("添加标签时发生错误:", str(e))
            return

    id3 = ID3(file_path)

    if id3.getall('APIC'):
        id3.delall('APIC')

    id3.add(APIC(encoding=0, mime='image/jpeg', type=3, data=data))

    id3.add(TPE1(encoding=3, text=songinfoDict['artist']))

    id3.add(TIT2(encoding=3, text=songinfoDict['name']))

    id3.add(TALB(encoding=3, text=songinfoDict['album']))

    id3.save(v2_version=3)
Exemplo n.º 8
0
  def encodeMP3(self, wavf, dstf, cover, meta):
    FNULL = open(os.devnull, 'w')
    subprocess.call(['lame', '-V2', wavf, dstf], stdout=FNULL, stderr=FNULL)
    FNULL.close()
    # tag MP3
    mm = TrackMeta(meta)
    mp3 = MP3(dstf, ID3=ID3)
    mp3["TIT2"] = TIT2(encoding=3, text=mm.title())
    mp3["TPE1"] = TPE1(encoding=3, text=mm.artist())
    mp3["TALB"] = TALB(encoding=3, text=mm.album())
    mp3["TPE2"] = TPE2(encoding=3, text=mm.albumartist())
    if mm.date():
      mp3["TDRC"] = TDRC(encoding=3, text=mm.date())
    mp3["TRCK"] = TRCK(encoding=3,
                       text=mm.tracknumber()+"/"+mm.tracktotal())
    mp3["TPOS"] = TPOS(encoding=3,
                       text=mm.discnumber()+"/"+mm.disctotal())

    # composer
    if mm.composer():
      mp3["TCM"] = TCM(encoding=3, text=mm.composer())

    # cover
    if cover:
      data = open(cover, 'rb').read()
      covr = []
      if cover.endswith('png'):
        mime = 'image/png'
      else:
        mime = 'image/jpeg'
      mp3.tags.add(APIC(encoding=3, mime=mime, type=3, desc=u'Cover', data=data))

    # save
    mp3.save()
def set_album_art(file_path, yt_id):

    picture = 'http://i3.ytimg.com/vi/' + yt_id[1:] + '/hqdefault.jpg'

    img_data = requests.get(picture).content

    with open('./music/temp.jpg', 'wb') as handler:
        handler.write(img_data)

    picture_path = './music/temp.jpg'
    audio_path = file_path[:-1] + '3'

    audio = MP3(audio_path, ID3=ID3)

    try:
        audio.add_tags()
    except error:
        pass

    audio.tags.add(
        APIC(mime='image/jpeg',
             type=3,
             desc=u'Cover',
             data=open(picture_path, 'rb').read()))
    # edit ID3 tags to open and read the picture from the path specified and assign it
    audio.save()  # save the current changes

    os.remove('./music/temp.jpg')
Exemplo n.º 10
0
    def setID3(self, lrc, info, path):
        tags = ID3(path)
        # remove old unsychronized lyrics
        if len(tags.getall("USLT")) != 0:
            tags.delall("USLT")

        if ('album' in info):
            tags.add(TALB(encoding=3, lang='', desc='', text=info['album'][0]))
        if ('title' in info):
            tags.add(TIT2(encoding=3, lang='', desc='', text=info['title'][0]))
        if ('artist' in info):
            tags.add(TPE1(encoding=3, lang='', desc='',
                          text=info['artist'][0]))
        if ('cover' in info):
            tags.add(
                APIC(encoding=3,
                     mime='image/png',
                     type=3,
                     desc='cover',
                     data=requests.get(info['cover'][0],
                                       stream=True).raw.read()))

        for key, values in tags.items():
            if key != 'APIC:cover':
                print('\t', key, ': ', values, sep='')

        tags.add(USLT(encoding=3, lang='eng', desc='aaa', text=lrc))
        tags.save()
Exemplo n.º 11
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
Exemplo n.º 12
0
    def setID3(self, info, path):
        tags = ID3(path)
        # remove old unsychronized lyrics
        if len(tags.getall("USLT")) != 0:
            tags.delall("USLT")

        if ('cover' in info):
            tags.add(
                APIC(encoding=3,
                     mime='image/png',
                     type=3,
                     desc='cover',
                     data=requests.get(info['cover'][0],
                                       stream=True).raw.read()))

        dic = {'title': TIT2, 'artist': TPE1, 'album': TALB, 'lyric': USLT}

        for k, T in dic.items():
            if k in info:
                tags.add(T(encoding=3, text=info[k][0]))
        for key in ['title', 'artist', 'album']:
            li = tags[dic[key].__name__].text
            print('\t{}: {}'.format(key.ljust(6), ', '.join(li)))

        tags.save()
Exemplo n.º 13
0
    def update_song_meta(self, name, dat=None):
        """ APIC:cover """
        dat = dat or {}
        song = ID3(name)
        before_update_size = helper.is_file_ok(name)
        tags = ['TIT2', 'TALB', 'TPE1']
        for tag in tags:
            if dat.get(tag) and dat.get(tag) != song.get(tag):
                song.add(
                    getattr(id3, tag)(encoding=Encoding.UTF16, text=dat[tag]))

        if not song.get('APIC:cover') and dat.get('APIC'):
            self.CP.G('update album picture')
            with open(dat.get('APIC'), 'rb') as h:
                cover_raw = h.read()
            if cover_raw:
                frame = APIC(encoding=Encoding.UTF16,
                             mime="image/jpeg",
                             desc="cover",
                             type=PictureType.COVER_FRONT,
                             data=cover_raw)
                song.add(frame)

        song.save()
        self.CP.C('-' * 32)
        after_size = helper.is_file_ok(name)
        for k, v in song.items():
            if 'APIC' not in k:
                self.CP.W(k, v)
        self.CP.G('update done: size from {} to {}, pic took {}'.format(
            before_update_size, after_size, after_size - before_update_size))
        self.CP.C('-' * 32)
Exemplo n.º 14
0
def get_song(song):
    print("Downloading Music(%s)..." % song['title'])
    filename = song['sha256'] + '.mp3'
    download(filename, song['url'])

    print("Downloading meta-data...")
    download('tmp.jpg', song['picture'])
    audio = MP3(filename, ID3=ID3)
    try:
        audio.add_tags()
    except error:
        pass

    audio.tags.add(
        APIC(
            encoding=3,  # 3 is for utf-8
            mime='image/jpeg',  # image/jpeg or image/png
            type=3,  # 3 is for the cover image
            desc=u'Cover',
            data=open('tmp.jpg', mode='rb').read()))
    audio.tags.add(TIT2(encoding=3, text=song['title']))
    audio.tags.add(TALB(encoding=3, text=song['albumtitle']))
    audio.tags.add(TPE1(encoding=3, text=song['artist']))
    audio.tags.add(TDRC(encoding=3, text=song['public_time']))
    audio.save()
Exemplo n.º 15
0
def addTags(file):
    try:
        audio = EasyMP3(file)
        audio.tags = None
        audio["artist"] = getTrack().user["username"] #depending on who uploaded the song, this may not always be the actual artist of the song
        audio["title"] = getTrack().title
        audio["genre"] = getTrack().genre
        audio.save()
        artworkURL = getTrack().artwork_url  #gets url of artwork for song provided...
        if "large" in artworkURL:  #...but we need to replace "large" with "t500x500"...
            artworkURL = artworkURL.replace("large", "t500x500")  #...to get a decent sized photo that isn't pixelated for the cover art of the mp3
        image_data = requests.get(artworkURL).content
        mime = 'image/jpeg'
        if '.jpg' in artworkURL:
            mime = 'image/jpeg'
        if '.png' in artworkURL:
            mime = 'image/png'
        audio = MP3(file, ID3=OldID3)
        audio.tags.add(
                APIC(
                    encoding=3,  #3 is for utf-8
                    mime=mime,
                    type=3,  #3 is for the cover image
                    desc='Cover',
                    data=image_data
                )
            )
        audio.save()
    except Exception as e:
        print(e)
Exemplo n.º 16
0
 def set_id3(self, path, resolution=480):
     """
 Assigns the ID3 metadata of the MP3 file
 Args:
   path: The path of the converted MP3 file
   resolution: The target resolution of the cover-art
 """
     tags = ID3(path)
     tags.delete()
     tags.add(TIT2(encoding=3, text=self.track))
     tags.add(TPE1(encoding=3, text=self.artist))
     tags.add(TPE2(encoding=3, text=self.artist))
     tags.add(TALB(encoding=3, text=self.album))
     tags.add(TCON(encoding=3, text=self.genre))
     tags.add(
         TRCK(encoding=3, text=self.track_number + '/' + self.track_count))
     tags.add(
         TPOS(encoding=3, text=self.disc_number + '/' + self.disc_count))
     tags.add(TDRC(encoding=3, text=self.release_date[0:4]))
     # Embed cover-art in ID3 metadata
     img_path = self.get_cover_image(resolution)
     tags.add(
         APIC(encoding=3,
              mime='image/jpg',
              type=3,
              desc=u'Cover',
              data=open(img_path, 'rb').read()))
     tags.save()
Exemplo n.º 17
0
def tag_file(fn, artist, album, title, lyrics, date, atype):
    try:
        audiofile = MP3(fn, ID3=EasyID3)
        audiofile.delete()
        audiofile.save()
        audiofile['title'] = title
        audiofile['album'] = album
        audiofile['artist'] = artist
        audiofile['albumartist'] = artist
        if date is not None:
            audiofile['date'] = date
        audiofile['discnumber'] = ['1/1']
        if atype == 'Single':
            audiofile['tracknumber'] = ['1/1']
        audiofile.save()
        audiofile = MP3(fn, ID3=ID3)
        audiofile.tags.add(
            APIC(encoding=3,
                 mime='image/jpeg',
                 type=3,
                 desc=u'Cover',
                 data=open('download.jpg', 'rb').read()))
        if lyrics is not None:
            audiofile.tags.add(USLT(lang='eng', text=lyrics))
        audiofile.save()
        os.rename(fn, artist + ' - ' + title + '.mp3')
        os.remove('download.jpg')
        return (True)
    except Exception:
        return (False)
Exemplo n.º 18
0
def download_api_mp3(audio_url, art_url, artist, path):
    r = rq.get(audio_url, stream=True)
    with open(path, "wb") as f:
        for chunk in r.iter_content(chunk_size=1024):
            if chunk:
                f.write(chunk)
    mp3 = MP3(path, ID3=ID3)
    try:
        mp3.add_tags()
    except error:
        pass
    if art_url is not None:
        art_url = "t500x500".join(
            art_url.rsplit("large", 1)
        )  # get high resolution artwork instead of the shitty low res one sc wants you to have
        img_response = rq.get(art_url, stream=True)
        with open("temp.jpg", "wb") as f:
            shutil.copyfileobj(img_response.raw, f)
        del img_response
        mp3.tags.add(
            APIC(mime="image/jpeg",
                 type=3,
                 desc=u"Cover",
                 data=open("temp.jpg", "rb").read()))
    mp3.tags.add(TPE1(encoding=3, text=f"{artist}"))
    mp3.save()
    return
Exemplo n.º 19
0
def tag(fname, title, artist, genre, arturl):

    try:
        tag = EasyID3(fname)

    except mutagen.id3.ID3NoHeaderError:
        tag = mutagen.File(fname, easy=True)
        tag.add_tags()

    tag['artist'] = artist
    tag['title'] = title

    # Giving the album the same name as
    # the title beacause
    # I cant find the album name
    tag['album'] = title
    tag['genre'] = genre
    tag.save()

    id3 = ID3(fname)

    imagename = str(title.replace("/", "\\") + "500x500.jpg")

    image = urllib.request.urlretrieve(arturl, imagename)
    print("\033[92m✔ Album art downloaded\033[0m")

    imagedata = open(imagename, "rb").read()

    id3.add(APIC(3, 'image/jpeg', 3, 'Front cover', imagedata))
    id3.save(v2_version=3)

    # Always leave the place better than you found it ;)
    os.remove(imagename)
Exemplo n.º 20
0
def addArtwork(fileName, like):
	imageURL = like.artworkURL

	largerImageURL = getLargerImage(imageURL)

	urllib.urlretrieve(largerImageURL, "temp.jpg")

	audio = MP3(fileName, ID3=ID3)

	# add ID3 tag if it doesn't exist
	try:
	    audio.add_tags()
	except error:
	    pass

	audio.tags.add(
	    APIC(
	        encoding=3, # 3 is for utf-8
	        mime='image/jpeg', # image/jpeg or image/png
	        type=3, # 3 is for the cover image
	        desc=u'Cover',
	        data=open('temp.jpg', 'rb').read()
	    )
	)
	audio.save()
Exemplo n.º 21
0
def get_cover(path, cover_path, composer, album):
    audio = MP3(path, ID3=ID3)
    print('try getting cover image from', cover_path)
    img = None
    try:
        img = requests.get(cover_path, headers=headers).content
        # img = requests.get(cover_path, headers=headers).content
    except error:
        print(error)
        return

    if audio.tags == None:
        audio.add_tags()
    audio.tags.add(
        APIC(
            encoding=3,
            mime='image/jpeg',
            type=3,
            desc=u'Cover',
            data=img,
        ))
    audio.tags.add(TPE1(text=composer))
    audio.tags.add(TAL(text=album))

    audio.save()
    def __update_metadata(self, path = str(), info = dict()):
        with open(path, 'r+b') as mp3f:
            mp3 = MP3(mp3f)
            id3 = ID3()

            track_num = info.get('trackNumber', 1)
            id3.add(TRCK(encoding=3, text=[track_num if track_num > 0 else 1]))

            id3.add(TIT2(encoding=3, text=info['title']))
            id3.add(TPE1(encoding=3, text=[info.get('artist', None)]))
            id3.add(TCOM(encoding=3, text=[info.get('composer', None)]))
            id3.add(TCON(encoding=3, text=[info.get('genre', None)]))
            id3.add(TAL(encoding=3, text=[info.get('album', None)]))

            year = info.get('year', 0)
            if year > 0:
                id3.add(TYER(encoding=3, text=[year]))
            
            if 'albumArtRef' in info and len(info['albumArtRef']) > 0:
                img_url = info['albumArtRef'][0]['url']
                if img_url:
                    req = requests.get(img_url, allow_redirects=True)
                    id3.add(APIC(encoding=3, mime='image/jpeg', type=3, data=req.content))
                    
            mp3.tags = id3
            mp3.save(mp3f)
Exemplo n.º 23
0
def add_id3_tags(t, file, cover):
	audio = ID3(file)

	# album
	audio.add(TALB(encoding=3, text=u'' + dict_cue['album']))

	# genre
	audio.add(TCON(encoding=3, text=u'' + dict_cue['genre']))

	# year
	audio.add(TYER(encoding=3, text=u'' + dict_cue['year']))

	# compilation
	audio.add(TCMP(encoding=3, text=u'' + str(dict_cue['compilation'])))

	# track number
	audio.add(TRCK(encoding=3, text=u'' + str(t+1) + '/' + str(len(dict_cue['songs']))))

	# artist
	if len(dict_cue['songs'][t]) == 3:
		audio.add(TPE1(encoding=3, text=u'' + dict_cue['songs'][t][1]))
	else:
		audio.add(TPE1(encoding=3, text=u'' + dict_cue['artist']))

	# song title
	if len(dict_cue['songs'][t]) == 3:
		audio.add(TIT2(encoding=3, text=u'' + dict_cue['songs'][t][2]))
	else:
		audio.add(TIT2(encoding=3, text=u'' + dict_cue['songs'][t][1]))

	# cover
	if cover:
		audio.add(APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=open(cover, 'rb').read()))

	audio.save()
Exemplo n.º 24
0
def copyFlacCover(flacFile, mpgFile):
    from mutagen.id3 import ID3, APIC
    from mutagen.flac import FLAC, Picture
    from mutagen.mp3 import MP3
    from mutagen.id3 import ID3

    audio = MP3(mpgFile, ID3=ID3)
    keys = [tag for tag in audio.keys() if 'APIC' in tag]
    for key in keys:
        del audio[key]
    audio.save()

    flacFile = FLAC(flacFile)
    pics = flacFile.pictures
    for img in pics:
        # Nur Frontcover kopieren!
        if img.type == 3:
            id3pic = APIC(3, img.mime, img.type, img.desc, img.data)
            print 'fuege der MP3-Datei {0} das Bild Typs {1} hinzu.'.format(
                mpgFile, img.type)
            audio = ID3(mpgFile)
            audio.add(id3pic)
            audio.save()
            audio.save()
    return
Exemplo n.º 25
0
    def _write_mp3_tags(self, path, track, tags=None):
        track = track["DATA"] if "DATA" in track else track

        if not tags:
            tags = self.get_track_tags(track)

        audio = MP3(path, ID3=EasyID3)
        audio.delete()
        EasyID3.RegisterTextKey("label", "TPUB")

        cover = tags["_albumart"]
        del tags["_albumart"]

        for key, val in tags.items():
            if val:
                audio[key] = str(val)
        audio.save()

        if cover:
            cover_handle = ID3(path)
            cover_handle["APIC"] = APIC(
                type=3,
                mime=cover["mime_type"],
                data=cover["image"]
            )
            cover_handle.save(path)

        return True
Exemplo n.º 26
0
def tag_file(filename, metadata):
    image = None
    if metadata['artwork_url']:
        download_file('artwork.jpg', metadata['artwork_url'], silent=True)
    if os.path.isfile('artwork.jpg'): image = open('artwork.jpg', 'rb').read()
    if filename.endswith('.mp3'):
        audio = MP3(filename, ID3=ID3)
        audio.add_tags()
        if image:
            audio.tags.add(
                APIC(encoding=3,
                     mime='image/jpeg',
                     type=3,
                     desc=u'Cover',
                     data=image))
        audio.tags["TIT2"] = TIT2(encoding=3, text=metadata['title'])
        audio.tags["TPE1"] = TPE1(encoding=3, text=metadata['artist'])
        audio.tags["TDRC"] = TDRC(encoding=3, text=metadata['year'])
        audio.tags["TCON"] = TCON(encoding=3, text=metadata['genre'])
        audio.save()
    elif filename.endswith('.flac'):
        audio = FLAC(filename)
        audio.add_tags()
        if image:
            audio.tags.add(
                APIC(encoding=3,
                     mime='image/jpeg',
                     type=3,
                     desc=u'Cover',
                     data=image))
        audio.tags['title'] = metadata['title']
        audio.tags['artist'] = metadata['artist']
        audio.tags['year'] = metadata['year']
        audio.tags['genre'] = metadata['genre']
        audio.save()
    elif filename.endswith('.m4a'):
        audio = MP4(filename)
        audio.add_tags()
        covr = []
        if image: covr.append(MP4Cover(image, MP4Cover.FORMAT_JPEG))
        audio.tags['covr'] = covr
        audio.tags['title'] = metadata['title']
        audio.tags['artist'] = metadata['artist']
        audio.tags['year'] = metadata['year']
        audio.tags['genre'] = metadata['genre']
        audio.save()
    if os.path.isfile('artwork.jpg'): os.remove('artwork.jpg')
Exemplo n.º 27
0
def modifyTags(songpath,
               pic,
               singername,
               songname,
               albumname,
               isalbum=False,
               albumdate='',
               belongcd='',
               cdidx=1,
               dicsnum=1):
    coverpath = "%s/%s - cover.jpg" % (musicpath, albumname)
    img = None
    if isalbum and os.path.exists(coverpath):
        img = open(coverpath, "rb")
    else:
        request = urllib.request.Request(pic)
        request.add_header(
            'User-agent',
            'Mozilla/5.0 (Macintosh; Intel) Gecko/20100101 Firefox/63.0')
        request.add_header('Cache-Control', 'max-age=0, no-cache')
        request.add_header('Host', 'y.qq.com')
        request.add_header('Referer', 'https://y.qq.com/n/yqq/toplist/4.html')
        img = urllib.request.urlopen(request)

    meta = None
    try:
        meta = mutagen.File(songpath)
    except (FileNotFoundError, mutagen.MutagenError):
        print('mutagen.MutagenError: ' '%s' '' % songpath)
        return

    try:
        meta.add_tags()
    except mutagen.MutagenError:
        None

    meta['TIT2'] = TIT2(  # 插入歌名
        encoding=1, text=[songname])
    meta['TPE1'] = TPE1(  # 插入第一演奏家、歌手、等
        encoding=1, text=[singername])
    meta['TALB'] = TALB(  # 插入专辑
        encoding=1, text=[albumname])
    meta['APIC'] = APIC(  # 插入图片
        encoding=1,
        mime='image/jpeg',
        type=3,
        desc=u'Cover',
        data=img.read())

    # write addition mp3 tag
    if isalbum:
        meta['TDRC'] = TDRC(  # 插入专辑年份
            encoding=1, text=[albumdate])
        meta['TRCK'] = TRCK(  # 插入曲目编号
            encoding=1, text=[belongcd])
        if dicsnum != 1:
            meta['TPOS'] = TPOS(  # 碟片编号
                encoding=1, text=['%02d/%d' % (cdidx, dicsnum)])
    meta.save()
Exemplo n.º 28
0
def tag_file(filename,
             artist,
             title,
             year=None,
             genre=None,
             artwork_url=None,
             album=None,
             track_number=None):
    """
    Attempt to put ID3 tags on a file.

    """

    try:
        audio = EasyMP3(filename)
        audio.tags = None
        audio["artist"] = artist
        audio["title"] = title
        if year:
            audio["date"] = str(year.encode('ascii', 'ignore'))
        if album:
            audio["album"] = album
        if track_number:
            audio["tracknumber"] = track_number
        if genre:
            audio["genre"] = genre
        audio.save()

        if artwork_url:

            artwork_url = artwork_url.replace('https', 'http')

            mime = 'image/jpeg'
            if '.jpg' in artwork_url:
                mime = 'image/jpeg'
            if '.png' in artwork_url:
                mime = 'image/png'

            if '-large' in artwork_url:
                new_artwork_url = artwork_url.replace('-large', '-t500x500')
                try:
                    image_data = requests.get(new_artwork_url).content
                except Exception as e:
                    # No very large image available.
                    image_data = requests.get(artwork_url).content
            else:
                image_data = requests.get(artwork_url).content

            audio = MP3(filename, ID3=OldID3)
            audio.tags.add(
                APIC(
                    encoding=3,  # 3 is for utf-8
                    mime=mime,
                    type=3,  # 3 is for the cover image
                    desc='Cover',
                    data=image_data))
            audio.save()
    except Exception as e:
        print(e)
Exemplo n.º 29
0
def main():
    global defaultPath

    parse = argparse.ArgumentParser(
        description='Downloader of youtube videos as mp3')
    parse.add_argument("-url", metavar="string", help="video url", type=str)
    parse.add_argument("-path",
                       metavar="string",
                       help="path to save file",
                       type=str)

    if not len(sys.argv) > 1:
        parse.print_help()
        input("Press [Enter] to exit...")
        return

    args = parse.parse_args()

    if not args.url:
        return
    path = args.path if args.path else defaultPath

    if not os.path.exists(path):
        os.mkdir(path)

    if not path[len(path) - 1] == '/':
        path += '/'

    video = YouTube(args.url)
    video.streams.get_audio_only().download(path)

    for file in os.listdir(path):
        ratio = SequenceMatcher(a=file, b=video.title).ratio()
        if ratio > 0.7:
            nPath = path + os.path.splitext(file)[0] + ".mp3"
            stream = ffmpeg.input(path + file).output(nPath).run()
            imgData = urllib.request.urlopen(video.thumbnail_url).read()

            audiofile = MP3(nPath, ID3=ID3)

            try:
                audiofile.add_tags()
            except error:
                pass

            try:
                tags = ID3(nPath)
            except ID3NoHeaderError:
                print("Adding ID3 header")
                tags = ID3()

            tags["TPE1"] = TPE1(encoding=3, text=u"{}".format(video.author))

            audiofile.tags.add(
                APIC(mime='image/jpeg', type=3, desc=u'Cover', data=imgData))
            audiofile.save()
            tags.save(nPath)

            os.remove(path + file)
Exemplo n.º 30
0
    def __handle_download_all(self):
        """
        Downloads all videos in the GUI video list to file location.

        This method creates a folder in the download location with all
        the audio files in the video list.

        The folder is in the format Youtube_Audio_Batch_Downloader_MM_DD_YYYY_hh_mm_ss
        """
        folder_name = generate_folder()

        if not os.path.isdir(self.__values[Input.DOWNLOAD_LOCATION]):
            sg.Popup('Invalid path. Unable to download.')
            return

        download_path = os.path.join(self.__values[Input.DOWNLOAD_LOCATION], folder_name)
        num_videos = len(self.__loaded_videos)
        current_progress_bar = 0
        progress_bar_iterator = ProgBar.MAX_VALUE.value / num_videos

        self.__window[Input.CURRENT_DOWNLOAD].update('Downloading: ')

        for video in self.__loaded_videos:
            title = self.__remove_special_char(video['title'])
            self.__window[Input.CURRENT_DOWNLOAD].update(f'Downloading: {video["title"]} ')
            video['audio'].download(download_path)

            video_file = download_path + f'\{title}.mp4'
            audio_file = download_path + f'\{title}.mp3'

            # Convert MP4 to MP3 file
            clip = AudioFileClip(video_file)
            clip.write_audiofile(audio_file)
            clip.close()

            os.remove(video_file)

            # Add thumbnail image to MP3 file
            response = urllib2.urlopen(video['thumbnail'])
            imagedata = response.read()
            audio = MP3(audio_file, ID3=ID3)
            audio.tags.add(
                APIC(
                    encoding=3,
                    mime='image/jpeg',
                    type=3,
                    desc=u'Cover',
                    data=imagedata
                )
            )
            audio.save()

            self.__video_img.update(data=video['image'])
            self.__video_title.update(video['title'])
            self.__window[ProgBar.PROGRESS_BAR].update_bar(current_progress_bar + progress_bar_iterator)
            current_progress_bar += progress_bar_iterator
        self.__window[Input.CURRENT_DOWNLOAD].update('Download completed!')
        sg.Popup('Download Completed!')
Exemplo n.º 31
0
def addPicture(audio_path, pafy_obj):
    """Add picture to the audio file provided with audio_path arguments
    Picture url will get retrived from the pafy object

    Arguments:
        audio_path {String} -- Path to the audio file to work with
        pafy_obj {Object} -- The pafy object of the current audio file
    Return:
        Doesn't return a value if operations are succeful but if it fail to fetch any image url 
        it return None and no operation is done with the audio file
    """
    if os.path.exists(audio_path)\
         and os.path.isfile(audio_path)\
              and audio_path.endswith('mp3'):
        if pafy_obj != None:
            audio = MP3(audio_path, ID3=ID3)

            # Download the cover image
            try:
                picture_url = None
                if (pafy_obj.bigthumbhd != None):
                    picture_url = pafy_obj.bigthumbhd
                    logging.debug("BigThumbHd")
                elif (pafy_obj.bigthumb != None):
                    picture_url = pafy_obj.bigthumb
                    logging.debug("BigThumb")
                elif (pafy_obj.thumb != None):
                    picture_url = pafy_obj.thumb
                    logging.debug("Thumb")
                else:
                    logging.debug("No thumbnail avaliable for the video")
                    return

                img = requests.get(picture_url)
                # extracting byte data from img response obj
                img = img.content
            except Exception as e:
                logging.debug("Error downloading cover art")
                logging.debug(e)

            # try adding id3 tags if not exists
            try:
                audio.add_tags()
            except error:
                logging.debug("ID3 Tag already exists for this audio file")

            # editing the id3 tag
            try:
                audio.tags.add(
                    APIC(mime='image/jpeg', type=3, desc=u'Cover', data=img))
                audio.save()
                logging.debug("Cover added")
            except error:
                logging.debug("Error adding coverart")
        else:
            logging.debug("Image path is invalid")
    else:
        logging.debug("audio path is invalid")
Exemplo n.º 32
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)
Exemplo n.º 33
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)))
Exemplo n.º 34
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
Exemplo n.º 35
0
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
Exemplo n.º 36
0
    def test_APIC(self):
        from mutagen.id3 import APIC

        frame = APIC(encoding=0, mime="m", type=3, desc="d", data=b"\x42")
        self.assertEqual(frame.HashKey, "APIC:d")
        frame._pprint()
Exemplo n.º 37
0
 def test_pprint(self):
     frame = APIC(
         encoding=0, mime=u"mime", type=3, desc=u"desc", data=b"\x42")
     self.assertEqual(frame._pprint(), u"cover front, desc (mime, 1 bytes)")