示例#1
0
 def get_id3_tags(self):
     self.tag_v1 = id3.Tag()
     self.tag_v1.parse(self.file, (1, None, None))
     self.tags_v1['Track number'] = [(self.tag_v1.track_num[0], 0, 50)]
     self.tags_v1['Title'] = '' if self.tag_v1.title is None else self.tag_v1.title
     self.tags_v1['Artist'] = '' if self.tag_v1.artist is None else self.tag_v1.artist
     self.tags_v1['Album'] = '' if self.tag_v1.album is None else self.tag_v1.album
     self.tags_v1['Genre'] = None if self.tag_v1.genre is None else self.tag_v1.genre.id
     date = self.tag_v1.recording_date
     self.tags_v1['Date'] = [(date.day, 1, 31), (date.month, 1, 12),
                             (date.year, 1950, 2020)] if date is not None else [(None, 1, 31), (None, 1, 12),
                                                                                (None, 1950, 2020)]
     self.tags_v1['Comments'] = self.tag_v1.comments.get('').text if self.tag_v1.comments.get('') is not None else ''
     self.tag_v2 = id3.Tag()
     self.tag_v2.parse(self.file, (2, None, None))
     self.tags_v2['Track number'] = [(self.tag_v2.track_num[0], 0, 50), (self.tag_v2.track_num[1], 0, 50)]
     self.tags_v2['Disc number'] = [(self.tag_v2.disc_num[0], 0, 100), (self.tag_v2.disc_num[1], 0, 100)]
     self.tags_v2['Title'] = '' if self.tag_v2.title is None else self.tag_v2.title
     self.tags_v2['Artist'] = '' if self.tag_v2.artist is None else self.tag_v2.artist
     self.tags_v2['Album'] = '' if self.tag_v2.album is None else self.tag_v2.album
     self.tags_v2['Album artist'] = '' if self.tag_v2.album_artist is None else self.tag_v2.album_artist
     self.tags_v2['Genre'] = None if self.tag_v2.genre is None else self.tag_v2.genre.id
     date = self.tag_v2.recording_date
     self.tags_v2['Date'] = [(date.day, 1, 31), (date.month, 1, 12),
                             (date.year, 1950, 2020)] if date is not None else [(None, 1, 31), (None, 1, 12),
                                                                                (None, 1950, 2020)]
     self.tags_v2['Comments'] = self.tag_v2.comments.get('').text if self.tag_v2.comments.get('') is not None else ''
     self.tags_v2['Publisher'] = '' if self.tag_v2.publisher is None else self.tag_v2.publisher
     self.tags_v2['Composer'] = '' if self.tag_v2.composer is None else self.tag_v2.composer
     self.tags_v2['BPM'] = [(self.tag_v2.bpm, 0, 10000)]
示例#2
0
def getmetadata(filee):
    global filefound
    tag = eye.Tag()
    try:
        tag.parse(filee)
        artist = tag.artist
        title = tag.title
        if artist == None:
            song_info1.config(text='Unknown Artist')
        else:
            song_info1.config(text=artist)
        if title == None:
            song_info.config(text='Unknown Title',
                             font=('AdobeClean-Bold', 11))
        else:
            song_info.config(text=title, font=('AdobeClean-Bold', 11))
        filefound = True
    except:
        pass
    try:
        load = MP3(filee)
        songbit = load.info.bitrate // 1000
        songbitrate.config(text=f'Bitrate: {songbit}kbps')
    except:
        return
示例#3
0
def nextinfo(info):
    if info == None:
        artistlbl.config(text='Artist: N/A')
        lengthlbl.config(text=f'Length: N/A')
        bitratelbl.config(text=f'Bitrate: N/A')
    else:
        try:
            song_load = MP3(info)
        except:
            info = info.replace("\\", "/")
        song_load = MP3(info)
        song_len1 = song_load.info.length
        styme1 = time.strftime('%M:%S', time.gmtime(song_len1))
        tagg = eye.Tag()
        tagg.parse(info)
        artist = tagg.artist
        if artist == None:
            artistlbl.config(text='Artist: Unknown Artist')
        else:
            artistlbl.config(text=f'Artist: {artist}')

        bitrate = song_load.info.bitrate / 1000

        lengthlbl.config(text=f'Length: {styme1}')
        bitratelbl.config(text=f'Bitrate: {int(bitrate)}kbps')
def main():
    args = get_script_arguments()
    if not os.path.exists(args.output_dir):
        os.makedirs(args.output_dir)
    elif args.force:
        shutil.rmtree(args.output_dir)
        os.makedirs(args.output_dir)
    else:
        print(f'{args.output_dir} already exists. Delete it first.')
        exit(1)
    musics = {}
    keep_count = 0
    delete_count = 0
    for input_filename in glob(args.input_dir + '/**/*.mp3', recursive=True):
        music_name = os.path.basename(input_filename)
        output_filename = os.path.join(args.output_dir, music_name)
        # just to avoid this warning: Invalid date: 20091201, we add version.
        tag = id3.Tag()
        tag.parse(input_filename)
        key = tag.artist + ' - ' + tag.title
        if key not in musics:
            musics[key] = 1.0
            print(f'KEEP {input_filename}.')
            keep_count += 1
            if not args.dry_run:
                shutil.copy2(input_filename, output_filename)
        else:
            print(f'DELETE {input_filename}.')
            delete_count += 1
    print(keep_count)
    print(delete_count)
    print('Completed.')
示例#5
0
文件: classic.py 项目: vicgc/Uforia
    def handleFile(self, f):
        parse_version = self.args.tag_version

        super(ClassicPlugin, self).handleFile(f, tag_version=parse_version)

        if not self.audio_file:
            return

        try:
            self.printHeader(f)
            printMsg("-" * 79)

            new_tag = False
            if (not self.audio_file.tag
                    or self.handleRemoves(self.audio_file.tag)):
                # No tag, but there might be edit options coming.
                self.audio_file.tag = id3.Tag()
                self.audio_file.tag.file_info = id3.FileInfo(f)
                self.audio_file.tag.version = parse_version
                new_tag = True

            save_tag = (self.handleEdits(self.audio_file.tag)
                        or self.args.force_update or self.args.convert_version)

            self.printAudioInfo(self.audio_file.info)

            if not save_tag and new_tag:
                printError("No ID3 %s tag found!" %
                           id3.versionToString(self.args.tag_version))
                return

            self.printTag(self.audio_file.tag)

            if save_tag:
                # Use current tag version unless a convert was supplied
                version = (self.args.convert_version
                           or self.audio_file.tag.version)
                printWarning("Writing ID3 version %s" %
                             id3.versionToString(version))

                self.audio_file.tag.save(version=version,
                                         encoding=self.args.text_encoding,
                                         backup=self.args.backup)

            if self.args.rename_pattern:
                # Handle file renaming.
                from eyed3.id3.tag import TagTemplate
                template = TagTemplate(self.args.rename_pattern)
                name = template.substitute(self.audio_file.tag, zeropad=True)
                orig = self.audio_file.path
                self.audio_file.rename(name)
                printWarning("Renamed '%s' to '%s'" %
                             (orig, self.audio_file.path))
            printMsg("-" * 79)
        except exceptions.Exception as ex:
            log.error(traceback.format_exc())
            if self.args.debug_pdb:
                import pdb
                pdb.set_trace()
            raise StopIteration()
示例#6
0
 def loadFile(self, _filePath, _tagVersion=None):
     if _tagVersion is None:
         _tagVersion = id3.ID3_V2_4
     self.tag = None
     self.info = None
     self.filePath = _filePath
     self.isCorrect = False
     self.isSave = False
     self.isNeedUpdate = False
     try:
         self.tag = id3.TagFile(
             uni.trEncode(self.filePath, fu.fileSystemEncoding),
             _tagVersion).tag
         self.info = mp3.Mp3AudioFile(
             uni.trEncode(self.filePath, fu.fileSystemEncoding)).info
     except:
         self.tag = id3.TagFile(self.filePath, _tagVersion).tag
         self.info = mp3.Mp3AudioFile(self.filePath).info
     if self.tag is None:
         self.isNeedUpdate = True
         self.isSave = True
         self.tag = id3.Tag()
         self.tag.parse(self.filePath, id3.ID3_ANY_VERSION)
     elif not self.tag.isV2():
         self.isNeedUpdate = True
         self.isSave = True
示例#7
0
 def get_image(self):
     """ Get an image for the file
         1) From the image URL in the DB
         2) From the information in the podcast RSS
         3) From the existing id3 tags
     """
     image = None
     if self.podcast.image:
         response = requests.get(self.podcast.image)
         image = Image.open(BytesIO(response.content))
     if not image and self.image:
         response = requests.get(self.image)
         image = Image.open(BytesIO(response.content))
     if not image:
         current_tag = id3.Tag()
         for entry in self.valid_id3s:
             current_tag.parse(self.file_name, version=entry)
             if not image and current_tag.images:
                 image = Image.open(
                     BytesIO(current_tag.images[0].image_data))
                 break
     if image:
         size = 400, 400
         image.thumbnail(size, Image.ANTIALIAS)
         image = image.convert('RGB')
         bytes_io = BytesIO()
         image.save(bytes_io, "JPEG")
         return bytes_io.getvalue()
     return None
示例#8
0
def tagSongs():
    ################################################
    #            Genre/Artist/Album/Song.mp3       #
    ################################################
    songs = getAllSongs()
    for s in songs:
        tag = id3.Tag()
        tag.parse(s)

        # Genre
        genre = "Unknown Genre" if tag.genre is None else str(
            tag.genre) if not str(tag.genre).startswith("(32)") else str(
                tag.genre)[4:]
        if not os.path.exists(f"{MUSIC_DIRECTORY}/{genre}"):
            os.mkdir(f"{MUSIC_DIRECTORY}/{genre}")

        # Artist
        artist = "Unknown Artist" if tag.artist is None else str(tag.artist)
        if not os.path.exists(f"{MUSIC_DIRECTORY}/{genre}/{artist}"):
            os.mkdir(f"{MUSIC_DIRECTORY}/{genre}/{artist}")

        # Album
        album = "Unknown Album" if tag.album is None else str(tag.album)
        if not os.path.exists(f"{MUSIC_DIRECTORY}/{genre}/{artist}/{album}"):
            os.mkdir(f"{MUSIC_DIRECTORY}/{genre}/{artist}/{album}")

        # Move the song to it's newly made directory
        os.rename(f"{MUSIC_DIRECTORY}/{s}",
                  f"{MUSIC_DIRECTORY}/{genre}/{artist}/{album}/{s}")
示例#9
0
 def set_mp3_info(self, name, artist, file, adl, music_type, all_musics, i, music_id, index):
     self.callback_progress_BAR(all_musics, i, '[COPY]' + name)
     if self.is_order:
         shutil.copy(self.getFilename(file[0], file[1], file[2], file[3]),
                     self.end_dir + getFixedNumStr(index + 1,all_musics) + "-" + validateTitle(name) + ' - ' + validateTitle(
                         artist) + "." +
                     str(music_id) + "." + music_type)
     else:
         shutil.copy(self.getFilename(file[0], file[1], file[2], file[3]),
                     self.end_dir + validateTitle(name) + ' - ' + validateTitle(artist) + "." + str(music_id) + "."
                     + music_type)
     if self.is_order:
         shutil.copy(self.getFilename(file[0], file[1], 'lrc', file[3]),
                     self.end_dir + getFixedNumStr(index + 1,all_musics) + "-" + validateTitle(name) + ' - ' + validateTitle(
                         artist) + "." +
                     str(music_id) + ".lrc")
     else:
         shutil.copy(self.getFilename(file[0], file[1], 'lrc', file[3]),
                     self.end_dir + validateTitle(name) + ' - ' + validateTitle(artist) + "." + str(music_id)
                     + ".lrc")
     tag = id3.Tag()
     if self.is_order:
         tag.parse(self.end_dir +  getFixedNumStr(index + 1,all_musics) + "-" + validateTitle(name) + ' - ' + validateTitle(artist)
                   + "." + str(music_id) + "." + music_type)
     else:
         tag.parse(self.end_dir + validateTitle(name) + ' - ' + validateTitle(artist) + "." + str(music_id) +
                   "." + music_type)
     tag.artist = artist
     tag.title = name
     tag.album = adl
     tag.save(encoding='utf-8')
     return
示例#10
0
def read_id3_artist(filename):
    """Module to read MP3 Meta Tags."""
    filename = filename
    filename.encode()
    tag = id3.Tag()
    tag.parse(filename)
    # print("Artist: \"{}\" Track: \"{}\"".format(tag.artist, tag.title))

    artist = tag.artist
    title = tag.title
    track_path = filename

    if artist is not None:
        artist.encode()
        artist = re.sub(u'`', u"'", artist)
    if title is not None:
        title.encode()
        title = re.sub(u'`', u"'", title)
    if track_path is not None:
        track_path.encode()
        track_path = re.sub(u'`', u"'", track_path)

    with open(new_file, 'a', newline='') as csvfile:
        stuff_to_write = csv.writer(csvfile,
                                    delimiter=',',
                                    quotechar='"',
                                    quoting=csv.QUOTE_ALL)
        stuff_to_write.writerow([artist, title, track_path])
示例#11
0
def add_tags(path, track, album, image, lyrics):
    try:
        genre = album['genres']['data'][0]['name']
    except (KeyError, IndexError):
        genre = ''

    tag = id3.Tag()
    tag.parse(path)
    tag.artist = track['artist']['name']
    tag.album = track['album']['title']
    tag.album_artist = album['artist']['name']
    try:
        tag.original_release_date = track['album']['release_date']
        tag.recording_date = int(track['album']['release_date'].split('-')[0])
    except:
        pass
    tag.title = track['title']
    tag.track_num = track['track_position']
    tag.disc_num = track['disk_number']
    tag.non_std_genre = genre
    tag.bpm = track['bpm']
    if lyrics:
        tag.lyrics.set(lyrics)
    tag.images.set(type_=3, img_data=image, mime_type='image/png')
    tag.save()
示例#12
0
def read_id3_artist(filename):
    """Module to read MP3 Meta Tags."""
    filename = filename
    filename.encode()
    tag = id3.Tag()
    tag.parse(filename)
    artist = tag.artist
    if artist is not None:
        artist.encode()
        artist = re.sub(u'`', u"'", artist)
        print("Artist: {}".format(artist.encode()))
    title = tag.title
    if title is not None:
        title.encode()
        title = re.sub(u'`', u"'", title)
        print("title: {}".format(title.encode()))
    track_path = filename
    if track_path is not None:
        track_path.encode()
        track_path = re.sub(u'`', u"'", track_path)
        print("Track Path: {}".format(track_path.encode()))
    duration = tag.duration
    if duration is not None:
        duration.encode()
        duration = re.sub(u'`', u"'", duration)
        print("Duration: {}".format(duration.encode()))
    return
示例#13
0
    def addMusicAuto(self):
        # inputFilepath = 'path/to/file/foobar.txt'
        # filename_w_ext = os.path.basename(inputFilepath)
        # filename, file_extension = os.path.splitext(filename_w_ext)
        # # filename = foobar
        # # file_extension = .txt
        #
        # path, filename = os.path.split(path / to / file / foobar.txt)
        # # path = path/to/file
        # # filename = foobar.txt
        tag = id3.Tag()
        print(glob.glob('musics/*.mp3'))
        for path in glob.glob('musics/*.mp3'):
            print(os.path.splitext(ntpath.basename(path))[0])
            print(path)
            tag.parse(path)
            if tag.artist is not None:
                artist = tag.artist
            else:
                artist = ''

            if tag.genre is not None:
                genre = tag.genre.name
            else:
                genre = ''

            if tag.artist_url is not None:
                url = tag.artist_url.decode("utf-8")
                print(url)
            else:
                url = 'null'

            music = Music(
                os.path.splitext(ntpath.basename(path))[0], genre, artist, url)
            self.addDocument(music)
示例#14
0
def checkthings(filename):
    """Module to Verify MP3 Meta Tags."""
    tag = id3.Tag()
    tag.parse(filename)
    test_version = ("Valid Tag Format: {}".format(
        id3.isValidVersion(tag.version)))  # noqa
    print(test_version)
    return id3.isValidVersion(tag.version)
def sort_songs_by_title(direcotry):
    mp3_files = get_mp3_files(direcotry)
    mp3_tuples = []

    for mp3 in mp3_files:
        tag = id3.Tag()
        tag.parse(mp3)
        mp3_tuples.append((mp3, tag.title))
    
    sorted_mp3_tuples = sorted(mp3_tuples, key = lambda x: x[1].lower())
    counter = 1
    for mp3_path, mp3_title in sorted_mp3_tuples:
        tag = id3.Tag()
        tag.parse(mp3_path)
        tag.track_num = counter
        tag.save()
        counter += 1
示例#16
0
 def clear_tags(self):
     """ Clear the id3 tags from a file
     """
     current_tag = id3.Tag()
     for entry in self.valid_id3s:
         current_tag.parse(self.file_name, version=entry)
         current_tag.clear()
         current_tag.save(filename=self.file_name, version=entry)
示例#17
0
    def meta(self):
        tag = id3.Tag()
        tag.parse(self.path)
        audio = MP3(self.path)

        self.title = tag.title
        self.intepret = tag.artist
        self.album = tag.album
        self.slength = audio.info.length
示例#18
0
def get_meta_data(file_path):
    """

    :param file_path:
    :return:
    """
    tag = id3.Tag()
    tag.parse(file_path)
    return tag.artist, tag.album, tag.title
示例#19
0
    def __init__(self, path):
        """
        :param path: The path to this .mp3 file.
        """

        self.path = path
        self.basename = os.path.basename(self.path)

        self.id_tag = id3.Tag()
        self.id_tag.parse(self.path)
示例#20
0
def put_music(music, response, music_folder=None, iter=None):
    if (music_folder is None):
        path = './files/music/{0}'.format(music['id'])
    else:
        path = '{0}/{1}'.format(music_folder, music['id'])
    mkdir_if_not_exists(path)

    file_name = music['title']
    file_name = file_name.replace('/', '|')
    file_name = sanitize(file_name)
    file_path = '{0}/{1}.mp3'.format(path, file_name)
    file = open(file_path, 'wb')
    file.write(response.content)
    file.close()

    print(file_path)
    print(music['title'])

    tag = id3.Tag()
    tag.parse(file_path)
    try:
        tag.version = id3.ID3_DEFAULT_VERSION
    except:
        tag.version = id3.ID3_V1
    artist = tag.artist
    title = tag.title

    if title is None:
        tag.title = music['title']
    if artist is None:
        tag.artist = music['artist']
    if len(music['track_covers']):
        curr_images = [y.description for y in tag.images]
        for image in curr_images:
            tag.images.remove(image)
        img_url = music['track_covers'][len(music['track_covers']) - 1]
        r = requests.get(img_url)
        tag.images.set(3, r.content, 'image/jpeg')

    track_name = '{0}-{1}-{2}.mp3'.format(
        tag.artist, tag.album if tag.album is not None else '', tag.title)
    tag.title = track_name

    try:
        tag.save()
    except:
        tag.version = id3.ID3_V1
        tag.save()

    track_name = track_name.replace('--', '-')
    track_name = track_name.replace('--', '-')
    track_name = sanitize(track_name)

    new_track_path = '{0}/{1}'.format(path, track_name)
    os.rename(file_path, new_track_path)
示例#21
0
def extract_id3(filepath):
    tag = id3.Tag()
    tag.parse(filepath)

    artist = tag.artist
    # print(artist)
    # title = tag.title
    # print(title)
    track_path = tag.file_info.name
    if not artist:
        print(track_path)
示例#22
0
def GetAlbumName(filename):
    tag = id3.Tag()
    tag.parse(filename)
    albumName = tag._getAlbum()
    artistName = tag._getArtist()
    print(albumName)
    if (albumName == None):
        if (artistName == None):
            return "Unsorted"
        else:
            return artistName
    else:
        return albumName
示例#23
0
def index(request):
    path = "/home/habilis/django-apps/musiconline/staticfiles/music"
    songs = os.listdir(path)
    tag = id3.Tag()
    titles = list()
    artists = list()
    for song in songs:
        tag.parse("staticfiles/music/" + song)
        titles.append(tag.title)
        artists.append(tag.artist)
    songs = zip(titles, artists)
    print(songs)
    template = loader.get_template('playmusic/index.html')
    return HttpResponse(template.render({'songs': list(songs)[:5]}, request))
示例#24
0
def scan_songs(path):
    songs = []
    for root, directories, filenames in os.walk(path):
        for filename in filenames:
            path = os.path.join(root, filename)
            tag = id3.Tag()
            tag.parse(path)
            album = tag.album
            artist = tag.artist
            title = tag.title
            genre = tag.genre
            song = Song(title, path, artist, album, genre)
            songs.append(song)
    return songs
示例#25
0
 def displayinfo(self):
     tag = id3.Tag()
     tag.parse(self.txtload_audio.get())
     self.txttitle.insert(INSERT, str(tag.title))
     self.txtartist.insert(INSERT, str(tag.artist))
     self.txtalbum.insert(INSERT, str(tag.album))
     self.txtalbum_artist.insert(INSERT, str(tag.album_artist))
     self.txtgenre.insert(INSERT, str(tag.genre))
     self.txtcomposer.insert(INSERT, str(tag.composer))
     self.txtyear.insert(INSERT, str(tag.recording_date).replace('None', ''))
     self.txtcomment.insert(INSERT, str(tag.comments[0].text))
     if str(tag.track_num):
         self.txttrack_num.insert(INSERT, str(tag.track_num[0]).replace('None', '0'))
     else:
         self.txttrack_num.insert(INSERT, str(tag.track_num[2]))
示例#26
0
def copyFilesInTextFile(pathToRead, files, name, path):
    try:
        textFile = open(join(path, name), 'w', encoding='utf-8')
        mp3Files, otherFiles = separateFileExtension(pathToRead, files)
        textFile.write(
            '==========================================CANCIONES==========================================\n'
        )
        for f in mp3Files:
            eyed3.log.setLevel("ERROR")
            tag = id3.Tag()
            tag.parse(join(pathToRead, f))
            """ if(tag.artist is not None):
                print("Artista: "+tag.artist)
            else:
                print("Artista: NO TIENE TAG") """
            """ if(tag.title is not None):
                print("Nombre: "+tag.title+"\n========================")
            else:
                print("Nombre: NO TIENE TAG \n========================") """
            textFile.write('  - Nombre del archivo: ' + f + '\n')
            if tag.title is not None:
                textFile.write('  - Titulo: ' + tag.title + '\n')
            else:
                textFile.write('  - Titulo: --\n')
            if tag.artist is not None:
                textFile.write('  - Artista: ' + tag.artist + '\n')
            else:
                textFile.write('  - Artista: --\n')
            textFile.write(
                '=================================================================================\n'
            )
        textFile.write(
            '========================================OTROS ARCHIVOS=======================================\n'
        )
        for o in otherFiles:
            textFile.write('  - Nombre del archivo: ' + o + '\n')
        textFile.close()
    except IOError as e:
        if e.errno == errno.EACCES:
            raise click.ClickException(
                'No tienes permiso de escritura en {}'.format(path))
        elif e.errno == errno.EIO:
            raise click.ClickException(
                '{} está protegido contra escritura'.format(path))
    except Exception as e:
        #traceback.print_exc()
        print("Error: {}".format(str(e)))
        pass
示例#27
0
    def tag_file(self):
        """ Add the tags to a file
            Set genre to 255 for compatibility with BMW iDrive

        """
        new_tag = id3.Tag()
        image = self.get_image()
        new_tag.artist = self.author
        new_tag.album_artist = self.author
        new_tag.title = self.title
        new_tag.album = self.podcast.name
        genre = id3.Genre(id=255, name=u"Podcast")
        new_tag.genre = genre
        if image:
            new_tag.images.set(3, image, 'image/jpeg', '')
        self.clear_tags()
        new_tag.save(filename=self.file_name, version=id3.ID3_V2_3)
示例#28
0
def sc_add_tags(path, track, image, lyrics=None):
    try:
        album_title = track['publisher_metadata']['album_title']
    except KeyError:
        album_title = ''

    tag = id3.Tag()
    tag.parse(path)
    tag.title = track.title
    tag.artist = track.artist
    tag.album = album_title
    tag.album_artist = track.artist if album_title else ''
    tag.original_release_date = track.created_at.split('T')[0].split(
        ' ')[0].replace('/', '-')
    tag.non_std_genre = track.get('genre', '')
    if lyrics:
        tag.lyrics.set(lyrics)
    tag.images.set(type_=3, img_data=image, mime_type='image/png')
    tag.save()
示例#29
0
def read_id3_artist(audio_file):
    """Module to read MP3 Meta Tags.

    Accepts Path like object only.
    """
    filename = audio_file
    tag = id3.Tag()
    tag.parse(filename)
    # =========================================================================
    # Set Variables
    # =========================================================================
    artist = tag.artist
    title = tag.title
    track_path = tag.file_info.name
    # =========================================================================
    # Check Variables Values & Encode Them and substitute back-ticks
    # =========================================================================
    if artist is not None:
        artist.encode()
        artistz = re.sub(u'`', u"'", artist)
    else:
        artistz = 'Not Listed'
    if title is not None:
        title.encode()
        titlez = re.sub(u'`', u"'", title)
    else:
        titlez = 'Not Listed'
    if track_path is not None:
        track_path.encode()
        track_pathz = re.sub(u'`', u"'", track_path)
    else:
        track_pathz = ('Not Listed, and you have an the worst luck, '
                       'because this is/should not possible.')
    # =========================================================================
    # print them out
    # =========================================================================
    try:
        if artist is not None and title is not None and track_path is not None:
            print('Artist: "{}"'.format(artistz))
            print('Track : "{}"'.format(titlez))
            print('Path  : "{}"'.format(track_pathz))
    except Exception as e:
        raise e
示例#30
0
 def __init__(self, audio_album, file, file_name, i):
     self.id = i
     self.file = file
     self.file_name = file_name
     self.tag_v1 = None
     self.tag_v2 = None
     self.tags_v1 = {}
     self.tags_v2 = {}
     self.get_id3_tags()
     tag = id3.Tag()
     tag.parse(file)
     self.title = 'untitled' if tag.title is None else tag.title
     self.album = 'untitled' if tag.album is None else tag.album
     self.artist = 'untitled' if tag.artist is None else tag.artist
     self.genre = 'not stated' if tag.genre is None else tag.genre.name
     self.image_data = None if tag.images.get('') is None else tag.images.get('').image_data
     self.number = 0 if tag.track_num is None or tag.track_num[0] is None else tag.track_num[0]
     self.submenu = lambda: SongPlaylistMenu(audio_album, self)
     self.menu = lambda: SongMenu(audio_album, self)