Example #1
0
def try_writemeta(vid, ext):
    filepath = os.path.join(path, 'output/file', ext, vid)
    if os.path.isdir(filepath):
        files = [
            file for file in next(os.walk(filepath))[2] if file.endswith(ext)
        ]
        if len(files) > 0:
            filename = files[0]
            if ext in ('mp3', ):
                logging.info(f'Trying to write metadata to {vid}.{ext}')
                info = get_raw_ytinfo(vid)
                meta = EasyID3(os.path.join(filepath, filename))
                meta['title'] = filename[:-(len(ext) + 1)]
                if info is not None:
                    if info['artist']:
                        meta['artist'] = info['artist']
                        meta['albumartist'] = info['artist']
                    if info['album']:
                        meta['album'] = info['album']
                meta.save()
                logging.info(f'Metadata {info} written into {vid}.{ext}')
Example #2
0
def addtags(filename, json_data):
    try:
        audio = MP4(filename)
        audio['\xa9nam'] = unicode(json_data['song'])
        audio['\xa9ART'] = unicode(json_data['primary_artists'])
        audio['\xa9alb'] = unicode(json_data['album'])
        audio['aART'] = unicode(json_data['singers'])
        audio['\xa9wrt'] = unicode(json_data['music'])
        audio['\xa9gen'] = unicode(json_data['language'])
        audio['purl'] = unicode(json_data['album_url'])
        audio['\xa9day'] = unicode(json_data['year'])
        audio['\xa9cmt'] = 'starring : {}'.format(unicode(json_data['starring']))
        audio['desc'] = parseHastags(json_data)
        cover_url = json_data['image'][:-11] + '500x500.jpg'
        fd = urllib.request.urlopen(cover_url)
        cover = MP4Cover(fd.read(), getattr(MP4Cover, 'FORMAT_PNG' if cover_url.endswith('png') else 'FORMAT_JPEG'))
        fd.close()
        audio['covr'] = [cover]
        audio.save()
        #‘\xa9lyr’ – lyrics
    except:
        os.rename(filename, filename[:-3]+'mp3')
        filename = filename[:-3] + 'mp3'
        try:
            audio = ID3(filename)
        except ID3NoHeaderError:
            audio = ID3()

        audio.add(TPE1(encoding=3, text=unicode(json_data['singers'])))
        audio.save(filename)
        audio = EasyID3(filename)
        audio['title'] = unicode(json_data['song'])
        audio['albumartist'] = unicode(json_data['primary_artists'])
        audio['album'] = unicode(json_data['album'])
        #audio['aART'] = unicode(json_data['singers'])
        audio['copyright'] = unicode(json_data['music'])
        #audio['copyright'] = unicode(json_data['starring'])
        audio['genre'] = unicode(json_data['label'])
        audio['date'] = unicode(json_data['year'])
        audio.save()
Example #3
0
 def parse(self, filename: Path) -> Metadata:
     """Extract the metadata from an MP3 file"""
     #print(filename)
     try:
         mp3_data = io.BytesIO(open(filename, 'rb').read())
     except IOError as err:
         raise InvalidMP3Exception(err)
     mp3info = EasyID3(mp3_data)
     try:
         artist = mp3info["artist"]
         title = mp3info["title"]
     except KeyError as err:
         raise InvalidMP3Exception(
             f"File: {filename.name} does not both title and artist info")
     if len(artist) == 0 or len(title) == 0:
         raise InvalidMP3Exception(
             f"File: {filename.name} does not both title and artist info")
     metadata = {
         "artist": artist[0],
         "title": title[0],
     }
     try:
         metadata["album"] = str(mp3info["album"][0])
     except KeyError:
         metadata["album"] = filename.parent.name
     del mp3info
     mp3_data.seek(0, io.SEEK_END)
     filesize = mp3_data.tell()
     mp3_data.seek(0)
     seg = AudioSegment.from_mp3(mp3_data)
     # duration is in milliseconds
     metadata["duration"] = len(seg)
     # bitrate is in Kbps
     metadata["bitrate"] = int(round(8.0 * filesize /
                                     float(metadata["duration"])))
     metadata["sample_width"] = seg.sample_width * 8
     metadata["channels"] = seg.channels
     # sample rate is in Hz
     metadata["sample_rate"] = seg.frame_rate
     return Metadata(**metadata) # type: ignore
Example #4
0
    def encode_tracks(self):
        """
        Using mutagen this encodes the .MP3
        files so that iTunes and other
        players can know what Artist,
        album, etc are.

        """
        print("Encoding...")
        i = 0
        for track in self.__album_data['track_titles']:
            file_name = self.__file_path + track + ".mp3"
            try:
                file_to_encode = EasyID3(file_name)
            except mutagen.id3.ID3NoHeaderError:
                print("\nFile didnt have ID3 tag, tagging now\n")
                file_to_encode = mutagen.File(file_name, easy=True)
                file_to_encode.add_tags()
            # add the mp3 tags to the audio files
            file_to_encode['tracknumber'] = str(i + 1)
            file_to_encode['title'] = track
            file_to_encode['artist'] = self.__album_data['artist']
            file_to_encode['album'] = self.__album_data['title']
            file_to_encode['date'] = self.__album_data['release_date'][2]
            file_to_encode.save()
            file_to_encode = MP3(file_name)
            print(self.__album_data['cover'])
            cover_data = open(self.__album_data['cover'], 'rb').read()
            file_to_encode.tags.add(
                APIC(
                    encoding=3,
                    mime='image/jpeg',
                    type=3,
                    desc=u'Cover',
                    data=cover_data
                )
            )
            file_to_encode.save()
            i += 1
        print("\nEncoding finished!\n")
Example #5
0
def addTagsToMP3(file_path, mp3_file_path, file_ext):
    """Gets the existing tags from the mp4 file and saves them to the mp3

    Arguments:
        mp4_file_path {str} -- Path for MP4 file
        mp3_file_path {str} -- Path for MP3 file
    """

    original_file_tags = None
    mp3_tags = EasyID3(mp3_file_path)
    if file_ext == "m4a":
        original_file_tags = EasyMP4(file_path)
        for k, v in original_file_tags.items():
            found_tag = EXTENSION_MAPPING.get(k, None)
            if found_tag is not None:
                resulting_tag = CONVERSION_TABLE[found_tag]["mp3"]
                mp3_tags[resulting_tag] = [v]
                print("Added tag {0}:{1} to mp3 {2}".format(
                    resulting_tag, v, mp3_file_path))
    elif file_ext in ["wma", "wmv"]:
        original_file_tags = ASF(file_path).tags
        for k, v in original_file_tags.items():
            found_tag = EXTENSION_MAPPING.get(k, None)
            if found_tag is not None:
                resulting_tag = CONVERSION_TABLE[found_tag]["mp3"]
                if file_ext in ["wma", "wmv"]:
                    if resulting_tag == "composer":
                        if mp3_tags.get(resulting_tag, None):
                            mp3_tags[resulting_tag] = ["{0}, {1}"].format(
                                mp3_tags[resulting_tag][0], v[0].value)
                        else:
                            mp3_tags[resulting_tag] = [v[0].value]
                    else:
                        mp3_tags[resulting_tag] = [v[0].value]
                print("Added tag {0}:{1} to mp3 {2}".format(
                    resulting_tag, v[0], mp3_file_path))
    else:
        return
    mp3_tags.save(mp3_file_path)
    print("MP3 tags saved to {0}".format(mp3_file_path))
def gather_audio_get_tag_info(audiofile):
    ''' function to intially extract info from the tags '''
    from mutagen.easyid3 import EasyID3
    from mutagen.mp3 import MP3
    import time
    import datetime
    from datetime import datetime

    import unicodedata
    import sys, traceback

    title = ''
    broadcastDate = ''
    episodeNumber = 0
    length = 60

    try:
        id3 = EasyID3(audiofile)
        mp3 = MP3(audiofile)

        length = mp3.info.length
        broadcastDate = unicodedata.normalize(
            'NFKD', mp3["COMM::'XXX'"].text[0]).encode('ascii', 'ignore')

        if broadcastDate[2] == '-':
            broadcastDate = '19' + broadcastDate

        title = unicodedata.normalize('NFKD', id3['title'][0]).encode(
            'ascii', 'ignore')
        episodeNumber = unicodedata.normalize('NFKD',
                                              id3['tracknumber'][0]).encode(
                                                  'ascii', 'ignore')
        logger.info('title: %s date: %s track: %s lenght: %s' %
                    (title, broadcastDate, episodeNumber, length))

    except:
        traceback.print_exc(file=sys.stdout)
        print 'died in gather_audio_get_tag_info'

    return title, broadcastDate, episodeNumber, length
Example #7
0
    def add_tags(self, filepath: str, track: dict):
        try:
            tags = EasyID3(filepath)
        except ID3NoHeaderError:
            tags = mutagen.File(filepath, easy=True)
            tags.add_tags()

        tags["tracknumber"] = str(
            track["trackNumber"]).encode("utf-8").decode("utf-8")
        tags["title"] = track["title"]
        tags["artist"] = track["artist"]
        tags["album"] = track["album"]
        tags["discnumber"] = str(
            track["discNumber"]).encode("utf-8").decode("utf-8")
        tags["genre"] = track["genre"]
        tags["composer"] = track["composer"]
        tags["albumartist"] = track["albumArtist"]
        if "beatsPerMinute" in track and not track["beatsPerMinute"] == 0:
            tags["bpm"] = str(
                track["beatsPerMinute"]).encode("utf-8").decode("utf-8")
        # TODO store Year. will have to use standard ID3 instead of easy
        tags.save(v2_version=3)
Example #8
0
def get_tags(fname):
    m = extre.search(fname)
    if m is None:
        raise ValueError('Unknown file type.')
    ext = m.group(1).lower()
    tags = {}
    if ext == 'mp3':
        try:
            info = EasyID3(fname)
            tags = list(info.iteritems())
        except ID3NoHeaderError:
            raise ValueError('No ID3 tags.')
    elif ext == 'ogg':
        info = OggVorbis(fname)
        tags = list(info.iteritems())
    elif ext == 'flac':
        info = FLAC(fname)
        tags = list(info.iteritems())
    elif ext == 'm4a':
        info = EasyMP4(fname)
        tags = list(info.iteritems())
    return tags
Example #9
0
 def generate_music(self):
     if 'attachments' in self.post:
         log.info('[AP] Извлечение аудио...')
         log.info('[AP] Данная функция находится в стадии тестирования.')
         session.http.cookies.update(dict(remixmdevice=self.remixmdevice))
         for attachment in self.post['attachments']:
             if attachment['type'] == 'audio':
                 n = 0
                 post_url = 'https://m.vk.com/wall%(owner_id)s_%(id)s' % self.post
                 soup = BeautifulSoup(
                     session.http.get(post_url).text, 'html.parser')
                 track_list = [
                     decode_audio_url(track.get('value'),
                                      api_vk.users.get()[0]['id'])
                     for track in soup.find_all(type='hidden')
                     if 'mp3' in track.get('value')
                 ]
                 dur_list = [
                     dur.get('data-dur') for dur in soup.find_all('div')
                     if dur.get('data-dur')
                 ]
                 name = sub(
                     r"[/\"?:|<>*]", '', attachment['audio']['artist'] +
                     ' - ' + attachment['audio']['title'] + '.mp3')
                 try:
                     file = download(track_list[n], out=name)
                 except urllib.error.URLError:
                     continue
                 try:
                     music = EasyID3(file)
                 except id3.ID3NoHeaderError:
                     music = File(file, easy=True)
                     music.add_tags()
                 music['title'] = attachment['audio']['title']
                 music['artist'] = attachment['audio']['artist']
                 music.save()
                 del music
                 self.tracks.append((name, dur_list[n]))
                 n += 1
Example #10
0
 def insertIntoDB(self, songlist):
     ' Insert these songs into the database '
     for song in songlist:
         audio = MP3(song)
         id3 = EasyID3(song)
         ' Check artist, title and album for this song '
         try:
             artist = str(id3['artist'][0])
         except KeyError:
             artist = None
         try:
             title = str(id3['title'][0])
         except KeyError:
             title = None
         try:
             album = str(id3['album'][0])
         except KeyError:
             album = None
         ' Check length and bitrate of the song '
         length = audio.info.length
         bitrate = audio.info.bitrate
         self.insertSong(artist, title, album, song, length, bitrate)
Example #11
0
def iterate_in_folder(path):
    ln = 0
    num = 0
    for item in os.listdir(path):
        if S_ISDIR(os.stat(os.path.join(path, item))[ST_MODE]):
            iterate_in_folder(os.path.join(path, item))
        elif item.endswith("mp3"):
            audio = MP3(os.path.join(path, item))
            print(str(item) + "  " + str(audio.info.length))
            try:
                mp3 = MP3(os.path.join(path, item))
                mp3.delete()
                mp3.save()
                audio = EasyID3(os.path.join(path, item))
                audio["artist"] = item[:item.index("-") - 1]
                audio['genre'] = ''
                audio['title'] = item[:item.index(".mp3")]
                audio['date'] = ''
                audio['album'] = ''
                audio.save(v2_version=3)
            except ValueError:
                print('error occured')
 def set_id3_data(self, convertedFilePath, songObj):
     # embed song details
     # ! we save tags as both ID3 v2.3 and v2.4
     # ! The simple ID3 tags
     audioFile = EasyID3(convertedFilePath)
     # ! Get rid of all existing ID3 tags (if any exist)
     audioFile.delete()
     # ! song name
     audioFile['title'] = songObj.get_song_name()
     audioFile['titlesort'] = songObj.get_song_name()
     # ! track number
     audioFile['tracknumber'] = str(songObj.get_track_number())
     # ! genres (pretty pointless if you ask me)
     # ! we only apply the first available genre as ID3 v2.3 doesn't support multiple
     # ! genres and ~80% of the world PC's run Windows - an OS with no ID3 v2.4 support
     genres = songObj.get_genres()
     if len(genres) > 0:
         audioFile['genre'] = genres[0]
     # ! all involved artists
     audioFile['artist'] = songObj.get_contributing_artists()
     # ! album name
     audioFile['album'] = songObj.get_album_name()
     # ! album artist (all of 'em)
     audioFile['albumartist'] = songObj.get_album_artists()
     # ! album release date (to what ever precision available)
     audioFile['date'] = songObj.get_album_release()
     audioFile['originaldate'] = songObj.get_album_release()
     # ! save as both ID3 v2.3 & v2.4 as v2.3 isn't fully features and
     # ! windows doesn't support v2.4 until later versions of Win10
     audioFile.save(v2_version=3)
     # ! setting the album art
     audioFile = ID3(convertedFilePath)
     rawAlbumArt = urlopen(songObj.get_album_cover_url()).read()
     audioFile['APIC'] = AlbumCover(encoding=3,
                                    mime='image/jpeg',
                                    type=3,
                                    desc='Cover',
                                    data=rawAlbumArt)
     audioFile.save(v2_version=3)
Example #13
0
    def c_record_audio(self, ):
        """docstring for c_asset_audio"""
        #raise Exception([self.cleaned_data['asset_contenttype'], self.cleaned_data['asset_contenttypesub']  ])

        keys_to_extract = ['artist', 'title', 'length']
        if self.cleaned_data[
                'record_contenttype'] == 'audio' and self.cleaned_data[
                    'record_contenttypesub'] not in Audio.FILE_TYPES:
            msg = u'Invalid audio type. Audio file should be in mp3 format.'
            self._errors['audio'] = self.error_class([msg])
            raise forms.ValidationError(msg)

        if self.cleaned_data['record_contenttypesub'] in Audio.FILE_TYPES:
            self.cleaned_data['length'] = 10
            from mutagen.easyid3 import EasyID3
            audio = self.cleaned_data['audio']
            song = EasyID3(audio.temporary_file_path())
            if not song:
                msg = u'Could not upload the audio file you submitted'
                self._errors['audio'] = self.error_class([msg])
                raise forms.ValidationError(msg)

            if not song.has_key('artist') or not song.has_key('title'):
                msg = u'Song should have following at least following tags: title, artist, length'
                self._errors['audio'] = self.error_class([msg])
                raise forms.ValidationError(msg)

            from mutagen.mp3 import MP3
            au = MP3(audio.temporary_file_path())
            #### to extract artist:au['TPE1'].text[0], title: au['TIT2'].text[0], album: au['TALB'].text[0]
            if au.info.length:
                self.cleaned_data['length'] = au.info.length
            else:
                self.cleaned_data['length'] = 10000
                msg = u'Could not get the length of the song. Please edit your song tags'
                self._errors['audio'] = self.error_class([msg])
                raise forms.ValidationError(msg)

        return True
Example #14
0
    def EditFile(self, mp3File, force=False):
        ''' return true to process the next file, False to quit. '''
        try:
            self.meta = fileDestination.Metadata(EasyID3(mp3File))
        except mutagen.id3.ID3NoHeaderError:
            f = mutagen.File(mp3File, easy=True)
            f.add_tags()
            self.meta = fileDestination.Metadata(f)

        # if self.args is not empty, pass along any settings that we
        # were given from the command line:
        for attr, val in self.args.items():
            self.meta[attr] = val

        if force:
            self.meta.Save()
            return True

        while 1:
            print "\n"
            # print as much of the path & file as we can without wrapping.
            print mp3File[-80:]
            print metadataFormat.format(self.meta)
            choice = GetInput("Enter item to edit [0 = next, q = quit]: ", str,
                              "0")
            if "0" == choice:
                self.meta.Save()
                return True
            elif "q" == choice.lower():
                self.meta.Save()
                return False
            else:
                # reset to zero-based so we can index into the list of attributes.
                try:
                    choice = int(choice) - 1
                    field = kFields[choice]
                    self.EditAttribute(*field)
                except (IndexError, ValueError):
                    continue
Example #15
0
def change_tags(root, file):
    audio = EasyID3(file)

    try:
        # ['tracknumber'] returns list with a string in format
        # 'track/total' i.e. '01/16'
        track = audio['tracknumber'][0].split('/')[0]

    except KeyError:
        track = '00'
        no_tracks.append((root, file))
    if len(track) == 1:
        track = '0' + track

    title = audio['title'][0]

    period_loc = file.rfind('.')
    extension = file[period_loc + 1:]
    new_title = ' '.join([track, title])

    if len(new_title) + 7 > 260:  # 260 is max length allowed for Windows files
        last_space = new_title.rfind('.')
        new_title = new_title[:last_space]

    new_title = new_title.replace('"', "'")
    new_title = re.sub(r'[\/:*?<>|]', '_', new_title)
    new_title = '.'.join([new_title, extension])

    try:
        print(new_title)
    except UnicodeEncodeError:
        print("can't be printed")

    if new_title != file:
        try:
            os.rename(file, new_title)
        except FileExistsError:
            duplicates.append((root, file))
            os.remove(root + "\\" + file)
Example #16
0
    def update_metadata(self, file_path=None):
        if file_path == None:
            file_path = self.file_name
        # Too lazy to read the spec, more efficient just to use ID3 to do
        # textual metadata and album art, but ¯\_(ツ)_/¯
        audio = EasyID3(file_path)
        audio['title'] = self.title
        audio['album'] = self.album
        audio['tracknumber'] = str(self.track_num)
        audio.save()

        if self.coverfile:
            audio = ID3(file_path)
            with open(self.coverfile, 'rb') as f:
                audio['APIC'] = 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=f.read()
                )
            audio.save()
Example #17
0
    def get_meta(file_path):
        local_meta = {}
        audio = EasyID3(file_path)
        for key in __get_all_keys():
            if key == 'audio': local_meta[key] = audio
            elif key == 'path': local_meta[key] = file_path
            elif key == 'filename':
                local_meta[key] = os.path.split(file_path)[1]

            elif key == 'title':
                local_meta[key] = __get_audio_meta(audio, key)
            elif key == 'artist':
                local_meta[key] = __get_audio_meta(audio, key)
            elif key == 'album':
                local_meta[key] = __get_audio_meta(audio, key)
            elif key == 'performer':
                local_meta[key] = __get_audio_meta(audio, key)
            elif key == 'composer':
                local_meta[key] = __get_audio_meta(audio, key)
            elif key == 'genre':
                local_meta[key] = __get_audio_meta(audio, key)
        return local_meta
Example #18
0
    def do(self):
        path = os.path.abspath(Secrets.SONG_DIRECTORY)
        files = os.listdir(path)
        for file in files:
            try:
                print(file)
                song = EasyID3(path + "/" + file)
                response = song
                genre, exist = Genre.objects.get_or_create(
                    title=response["genre"][0].title())
                artist_obj = self.get_artist_id(response['artist'][0], genre)
                album_obj, exist = Album.objects.get_or_create(
                    album_name=response['album'][0],
                    date=response["date"][0][0:4],
                    artist_id=artist_obj)
                obj, exist = Song.objects.get_or_create(
                    name=response['title'][0],
                    target=self.upload_file_path(response['title'][0], file),
                    album_id=album_obj)

            except Exception as e:
                print(e)
Example #19
0
    def checkdir(self, path, submit):
	import os, sys
	import traceback
	from mutagen.easyid3 import EasyID3

        from traceback import print_exc
        from mutagen.mp3 import MP3
        print "Scanning", path
	t = []
        i=0

        for path, dirs, files in os.walk(path):
          files.sort()
          for fn in files:
            if not fn.lower().endswith('.mp3'): continue
            ffn = os.path.join(path, fn)
            try:
                mp3 = MP3(ffn)
            except KeyboardInterrupt:
                raise
            except Exception, err:
                rep.error(ffn)
            else:
                if mp3.tags is None:
                    print "ERROR: No mp3 tags here"
                else:
#    	            print ffn
                    id3 = EasyID3(ffn)
                    if id3:
#                      print id3["title"], id3["artist"]
                      t2 = TrackInfo(i)
		      t2.name = id3["title"]
		      t2.artist = id3["artist"]
		      t2.album = id3["album"]
		      t2.length = mp3.info.length
		      t2.bitrate = mp3.info.bitrate
		      t2.path = ffn
		      t.append(t2)
		      i += 1
Example #20
0
def create_info_str(piece, files):
    info_str = f'"{piece}"'

    try:  # if artist can be read from first file add it to info_str
        info_str += f' by {EasyID3(files[0])["artist"][0]}'
    except KeyError:  # else just pass
        pass

    try:  # if album can be read from first file add it to info_str
        info_str += f' from album "{EasyID3(files[0])["album"][0]}" '
    except KeyError:  # else just pass
        pass

    try:  # if length can be read from files sum it up and add it to info_str
        play_time = 0
        for entry in files:
            play_time += int(EasyID3(entry)["length"][0])
        info_str += f' ({get_time_str_from_ms(play_time)})'
    except KeyError:  # else just pass
        pass

    return info_str
Example #21
0
    def read_tags(self):
        m = EasyID3(self.file_path)
        self.tag = MusicTag()

        self.tag.title = self.try_get_tag('title', m)
        self.tag.album = self.try_get_tag('album', m)
        self.tag.artist = self.try_get_tag('artist', m)

        try:
            self.tag.track = int(self.try_get_tag('tracknumber', m))
        except:

            # try to parse the track number from the file name
            import re
            title_re = re.compile("""(?P<number>[0-9]{1,3}) ?-? ?.+\.mp3""")
            m = title_re.match(self.filename)
            if m:
                self.tag.track = int(m.group("number"))
            else:
                print("Track number not found in tag")

        self.tag.generate_hash()
Example #22
0
def get_tag(file):
    """
    Returns the id3 tag information for the given file, if possible
    :param file: File whose id3 information is desired
    :return: dictionary of the form: {id3 tag : id3 value}
    """
    return_dict = dict()
    if file.endswith(".mp3"):
        audio = MP3(file)
        return_dict["length"] = audio.info.length
        return_dict["bitrate"] = audio.info.bitrate
        audio = EasyID3(file)
        for (key, value) in audio.iteritems():
            if len(value) == 1:
                return_dict[key] = filter(lambda x: x in string.printable,
                                          value[0])
            else:
                return_dict[key] = [
                    filter(lambda x: x in string.printable, localString)
                    for localString in value
                ]
    return return_dict
Example #23
0
def tag_mp3(source_file,
            artist,
            title,
            url="",
            album="",
            year="",
            comment="",
            genres=""):
    try:
        audio = EasyID3(source_file)
    except mutagen.id3.ID3NoHeaderError:
        audio = mutagen.File(source_file, easy=True)
        audio.add_tags()

    audio["artist"] = artist
    audio["title"] = title
    audio["genre"] = genres
    audio["website"] = url
    audio["copyright"] = "Deep South Sounds"
    audio["album"] = album

    audio.save(v1=2)
Example #24
0
    def _get_tags(self, file_path, tag=taglib):
        tag = tag or mutagen
        _logger.debug('Scanning file "%s"', file_path)
        try:
            song = tag.File(file_path)
            if not song:
                raise
        except:
            _logger.warning('Error while opening file "%s"',
                            file_path,
                            exc_info=True)
            return False, {}
        if tag.__name__ == "taglib":
            return song, song.tags
        else:
            try:
                song_tags = EasyID3(file_path) or {}
            except:
                song_tags = song.tags or {}

            song_tags = {k.upper(): v for k, v in song_tags.items()}
            return song, song_tags
Example #25
0
    def addFiles(self):
        files, _ = QFileDialog.getOpenFileNames(
            self, self.tr("Select Music Files"),
            QDesktopServices.storageLocation(QDesktopServices.MusicLocation),
            self.tr("Media Files (*.mp3 *.mp4 *.aac)")
        )
        if not files:
            return

        for mediafile in files:
            title = "unknown"
            artist, album, year = "", "", ""
            try:
                tag = EasyID3(mediafile)
                title = tag['title'][0]
                artist = tag['artist'][0]
                album = tag['album'][0]
                year = tag['date'][0]
            except:
                pass


            titleItem = QTableWidgetItem(title)
            titleItem.setFlags(titleItem.flags() ^ Qt.ItemIsEditable)
            artistItem = QTableWidgetItem(artist)
            artistItem.setFlags(artistItem.flags() ^ Qt.ItemIsEditable)
            albumItem = QTableWidgetItem(album)
            albumItem.setFlags(albumItem.flags() ^ Qt.ItemIsEditable)
            yearItem = QTableWidgetItem(year)
            yearItem.setFlags(yearItem.flags() ^ Qt.ItemIsEditable)

            currentRow = self.musicTable.rowCount()
            self.musicTable.insertRow(currentRow)
            self.musicTable.setItem(currentRow, 0, titleItem)
            self.musicTable.setItem(currentRow, 1, artistItem)
            self.musicTable.setItem(currentRow, 2, albumItem)
            self.musicTable.setItem(currentRow, 3, yearItem)
        self.engine.play_list_add(files)
        self.play_action()
Example #26
0
def writeMP3Tags(filename, tags, imageUrl):
    handle = MP3(filename, ID3=EasyID3)
    handle.delete()
    # label is not supported by easyID3, so we add it
    EasyID3.RegisterTextKey("label", "TPUB")
    # tracknumber and total tracks is one tag for ID3
    tags['tracknumber'] = f'{str(tags["tracknumber"])}/{str(tags["totaltracks"])}'
    del tags['totaltracks']

    for key, val in tags.items():
        handle[key] = str(val)
    handle.save()
    if imageUrl:
        image = getCoverArt(imageUrl, filename, 1500) # TODO: write to temp folder?
        handle= MP3(filename)
        handle["APIC"] = mutagen.id3.APIC(
                                        encoding=3, # 3 is for utf-8
                                        mime='image/png',
                                        type=3, # 3 is for the cover image
                                        data=image)
        handle.save()
    return True
Example #27
0
def embed_mp3(music_file, meta_tags):
    """Embed metadata to MP3 files."""
    # EasyID3 is fun to use ;)
    audiofile = EasyID3(music_file)
    audiofile['artist'] = meta_tags['artists'][0]['name']
    audiofile['albumartist'] = meta_tags['artists'][0]['name']
    audiofile['album'] = meta_tags['album']['name']
    audiofile['title'] = meta_tags['name']
    audiofile['tracknumber'] = [meta_tags['track_number'],
                                meta_tags['total_tracks']]
    audiofile['discnumber'] = [meta_tags['disc_number'], 0]
    audiofile['date'] = meta_tags['release_date']
    audiofile['originaldate'] = meta_tags['release_date']
    audiofile['media'] = meta_tags['type']
    audiofile['author'] = meta_tags['artists'][0]['name']
    audiofile['lyricist'] = meta_tags['artists'][0]['name']
    audiofile['arranger'] = meta_tags['artists'][0]['name']
    audiofile['performer'] = meta_tags['artists'][0]['name']
    audiofile['website'] = meta_tags['external_urls']['spotify']
    audiofile['length'] = str(meta_tags['duration_ms'] / 1000)
    if meta_tags['publisher']:
        audiofile['encodedby'] = meta_tags['publisher']
    if meta_tags['genre']:
        audiofile['genre'] = meta_tags['genre']
    if meta_tags['copyright']:
        audiofile['copyright'] = meta_tags['copyright']
    if meta_tags['isrc']:
        audiofile['isrc'] = meta_tags['external_ids']['isrc']
    audiofile.save(v2_version=3)
    audiofile = ID3(music_file)
    try:
        albumart = urllib.request.urlopen(meta_tags['album']['images'][0]['url'])
        audiofile["APIC"] = APIC(encoding=3, mime='image/jpeg', type=3,
                                 desc=u'Cover', data=albumart.read())
        albumart.close()
    except IndexError:
        pass
    audiofile.save(v2_version=3)
    return True
def set_tags(filename, title, album_name, artist_name, index, cover):
    audio = eyed3.load(filename)

    if (audio.tag == None):
        audio.initTag()

    audio.tag.title = title

    audio.tag.album = album_name

    audio.tag.artist = artist_name

    if cover:
        audio.tag.images.set(3, open(cover, 'rb').read(), 'image/jpeg')

    audio.tag.save()

    audio = EasyID3(filename)

    audio["tracknumber"] = str(index)

    audio.save()
Example #29
0
def updateTags( fullFileName, podName ):

	id3Tag = None
	
	# try open tags, if fails, create new
	try:
		id3Tag = EasyID3( fullFileName )
	except:
		id3Tag = mutagen.File( fullFileName, easy = True )
		if id3Tag == None:
			syslog.syslog( syslog.LOG_ERR, "Failed to create id3 tags" )
			return
		id3Tag.add_tags()

	# extract file name without extension from full file name
	fileName = os.path.split( fullFileName )[ 1 ]
	title = os.path.splitext( fileName )[ 0 ]

	id3Tag[ "title" ] = unicode("{}".format( title ), "utf-8")
	id3Tag[ "artist" ] = unicode("{}".format( podName ), "utf-8")

	id3Tag.save()
Example #30
0
def GetMetadataFields(f):
    ''' opens the file named 'f', then returns a dict with values for the following
      metadata contained in the file:
      artistalbum
      title
      tracknumber 
      genre
      bitrate
      date
      length
   '''
    audio = MP3(f)

    try:
        meta = EasyID3(f)
    except mutagen.id3.ID3NoHeaderError:
        meta = {}

    metaDict = {}
    metaFields = "artist album title tracknumber genre date".split()
    for field in metaFields:
        try:
            metaDict[field] = meta[field][0]
        except KeyError:
            metaDict[field] = u""

    try:
        length = MsToMinSec(meta['length'][0])
    except KeyError:
        length = u"--:--"
    metaDict['length'] = length
    metaDict['bitrate'] = audio.info.bitrate

    # the tracknumber value may be in the format 'x/y' -- we only want the 'x'
    if metaDict['tracknumber']:
        metaDict['tracknumber'] = GetTrackNumber(metaDict['tracknumber'])

    return metaDict