当前位置: 首页>>代码示例>>Python>>正文


Python tinytag.TinyTag类代码示例

本文整理汇总了Python中tinytag.TinyTag的典型用法代码示例。如果您正苦于以下问题:Python TinyTag类的具体用法?Python TinyTag怎么用?Python TinyTag使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了TinyTag类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: getMetaData

def getMetaData(fullname, playlists):
    log.info('accessing metadata...')
    index = 0
    tagInfo = []
    for track in playlists:
        name= playlists[track]
        if os.path.isfile(name):
            try:
                filename = os.path.basename(name)
                log.success('-------------------------')
                tag = TinyTag.get(name)
                if tag.title != '' or tag.artist != '':
                    song = str(tag.title+':'+tag.artist)
                    tagInfo.append(song)
                    log.warn('tag info:', filename.encode("ascii", "ignore"))
                    log.info('Artist:', tag.artist)
                    log.info('Album:', tag.album)
                    log.info('Title:', tag.title.encode("ascii", "ignore"))
                    log.info('Track number:', tag.track)
                    index += 1
                else:
                    log.warn('WARN: no id3 info provide')

            except Exception as e:
                log.err("An error occurred while getting metadata of the file:", name)
                log.err("Error:", e)
        else:
            log.err("The file: %s does not exist, check the path or filename" % (name))
    print
    log.err('track processing:', str(index))
    saveMetaData(fullname, tagInfo, index)
    return tagInfo
开发者ID:diniremix,项目名称:musikker,代码行数:32,代码来源:tags.py

示例2: main

def main():
    args = parser.parse_args()
    args.foldername = os.path.expanduser(args.foldername)
    new_foldername = args.foldername
    # keep a list of all cues and flacs
    file_lists = get_music(new_foldername=new_foldername)
    music_filenames = file_lists['mp3']
    # now, for each file, get the mp3 tags and get the date created
    music_dataframe = []
    for music_file in music_filenames:
        try:
            tag = TinyTag.get(music_file)
        except Exception as e:
            print e
            next
        if tag.artist is not None:
            artist = tag.artist.encode('ascii', 'ignore')
        if tag.album is not None:
            album = tag.album.encode('ascii', 'ignore')
        if tag.title is not None:
            title = tag.title.encode('ascii', 'ignore')
        date_changed = os.path.getmtime(music_file)
        music_dataframe.append({'artist':artist,'album':album,'title':title,'date':date_changed})


    music_dataframe = DataFrame(music_dataframe)
    music_dataframe.to_csv("mp3_tags.csv")
开发者ID:CatherineH,项目名称:chusic,代码行数:27,代码来源:get_info.py

示例3: db_check

def db_check():
        mp3s = get_mp3_list()
        for d, mp3 in mp3s:
                fullpath = os.path.join(d,mp3)
                data = db_get(fullpath, 'fullpath')
                if not data:
                        print 'adding: ', fullpath
                        data = {
                                'fullpath': fullpath,
                                'title': mp3,
                                'description': '',
                        }
                        try:
                                date_part = mp3.split('.')[0]
                                date_obj = datetime.strptime(date_part, '%Y-%m-%d_%H-%M-%S')
                                #data['date'] = datetime.strftime(date_obj, '%a %b %d, %Y at %I:%M %p')
                                data['date'] = date_obj
                        except:
                                date_obj = datetime.fromtimestamp(os.path.getctime(fullpath))
                                #data['date'] = datetime.strftime(date_obj, '%a %b %d, %Y at %I:%M %p')
                                data['date'] = date_obj
                        tag = TinyTag.get(fullpath)
                        m, s = divmod(tag.duration, 60)
                        h, m = divmod(m, 60)
                        data['duration'] = "%d:%02d:%02d" % (h, m, s)
                        db_insert(data)
        delete = []
        for mp3 in db_get_all():
                if not os.path.exists(mp3['fullpath']):
                        delete.append(mp3['fullpath'])
        for d in delete:
                print 'removing: ', d
                db_remove(d)
开发者ID:sdockray,项目名称:vpr-archive,代码行数:33,代码来源:server.py

示例4: folderTraversal

 def folderTraversal(self, folderPath):
     for root, subdir, files in os.walk(folderPath):
         hasMusic = False
         albumName = ""
         for f in files:
             fullPath = os.path.join(root, f)
             try:
                 metadata = TinyTag.get(fullPath)
             except LookupError:
                 # File is not a valid audio file, skip
                 continue
             metadata.album = str(metadata.album)
             self.trackIDList.add(utils.genID(metadata))
             if self.config.filter.check(metadata) and not (metadata in self.record):
                 albumName = metadata.album
                 if albumName not in self.albums:
                     self.albums[albumName] = objects.Album(albumName)
                 newTrack = objects.Track(metadata, fullPath)
                 self.albums[albumName].add(newTrack)
                 hasMusic = True
                 self.progress.incTotal()
         if hasMusic:
             # Handle cover image
             self.albums[albumName].coverFile = self.__detectCoverFile(root)
             logging.info("Album: %s with %d song(s)" %
                          (albumName, len(self.albums[albumName].tracks)))
开发者ID:tuankiet65,项目名称:pyMusicSync,代码行数:26,代码来源:sync.py

示例5: getSongInfo

def getSongInfo(filepath):
    tag = TinyTag.get(filepath)
    # make sure everthing returned (except length) is a string
    for attribute in ['artist','album','title','track']:
        if getattr(tag, attribute) is None:
            setattr(tag, attribute, '')
    return Metainfo(tag.artist, tag.album, tag.title, str(tag.track), tag.length)
开发者ID:cheese83,项目名称:cherrymusic,代码行数:7,代码来源:metainfo.py

示例6: test_duration_with_vlc

 def test_duration_with_vlc(self):
     import vlc
     v = vlc.Instance()
     mp = MusicPlayer(self.config)
     albums = mp.get_albums_and_songs()
     # VLC Start
     start_time = time.time()
     for album in albums:
         print(colorstring("Album: " + album.title, Colors.GREEN))
         for song in album.getsonglist():
             print(colorstring("\t" + str(song.title), Colors.BLUE))
             media = v.media_new(song.filepath)
             media.parse()
             print("\tsong duration: " + str(media.get_duration()))
     print(colorstring("--- VLC took %s seconds ---" % round((time.time() - start_time), 5), Colors.RED))
     # VLC End
     # TinyTag Start
     start_time = time.time()
     for album in albums:
         print(colorstring("Album: " + album.title, Colors.GREEN))
         for song in album.getsonglist():
             print(colorstring("\t" + str(song.title), Colors.BLUE))
             tinytag = TinyTag.get(song.filepath, False, True)
             print("\tsong duration: " + str(round(tinytag.duration * 1000)))
     print(colorstring("--- TinyTag took %s seconds ---" % round((time.time() - start_time), 5), Colors.RED))
开发者ID:MelleDijkstra,项目名称:PythonMusicPlayer,代码行数:25,代码来源:tinytag_tests.py

示例7: _fetch_embedded_image

 def _fetch_embedded_image(self, path):
     filetypes = ('.mp3',)
     max_tries = 3
     header, data, resized = None, '', False
     try:
         files = os.listdir(path)
         files = (f for f in files if f.lower().endswith(filetypes))
         for count, file_in_dir in enumerate(files, start=1):
             if count > max_tries:
                 break
             filepath = os.path.join(path, file_in_dir)
             try:
                 tag = TinyTag.get(filepath, image=True)
                 image_data = tag.get_image()
             except IOError:
                 continue
             if not image_data:
                 continue
             _header, _data = self.resize_image_data(
                 image_data, (self.IMAGE_SIZE, self.IMAGE_SIZE))
             if _data:
                 header, data, resized = _header, _data, True
                 break
     except OSError:
         pass
     return header, data, resized
开发者ID:devsnd,项目名称:cherrymusic,代码行数:26,代码来源:albumartfetcher.py

示例8: api_fetchalbumart

    def api_fetchalbumart(self, directory):
        _save_and_release_session()
        default_folder_image = "../res/img/folder.png"

        log.i('Fetching album art for: %s' % directory)
        filepath = os.path.join(cherry.config['media.basedir'], directory)

        if os.path.isfile(filepath):
            # if the given path is a file, try to get the image from ID3
            tag = TinyTag.get(filepath, image=True)
            image_data = tag.get_image()
            if image_data:
                log.d('Image found in tag.')
                header = {'Content-Type': 'image/jpg', 'Content-Length': len(image_data)}
                cherrypy.response.headers.update(header)
                return image_data
            else:
                # if the file does not contain an image, display the image of the
                # parent directory
                directory = os.path.dirname(directory)

        #try getting a cached album art image
        b64imgpath = albumArtFilePath(directory)
        img_data = self.albumartcache_load(b64imgpath)
        if img_data:
            cherrypy.response.headers["Content-Length"] = len(img_data)
            return img_data

        #try getting album art inside local folder
        fetcher = albumartfetcher.AlbumArtFetcher()
        localpath = os.path.join(cherry.config['media.basedir'], directory)
        header, data, resized = fetcher.fetchLocal(localpath)

        if header:
            if resized:
                #cache resized image for next time
                self.albumartcache_save(b64imgpath, data)
            cherrypy.response.headers.update(header)
            return data
        elif cherry.config['media.fetch_album_art']:
            #fetch album art from online source
            try:
                foldername = os.path.basename(directory)
                keywords = foldername
                log.i(_("Fetching album art for keywords {keywords!r}").format(keywords=keywords))
                header, data = fetcher.fetch(keywords)
                if header:
                    cherrypy.response.headers.update(header)
                    self.albumartcache_save(b64imgpath, data)
                    return data
                else:
                    # albumart fetcher failed, so we serve a standard image
                    raise cherrypy.HTTPRedirect(default_folder_image, 302)
            except:
                # albumart fetcher threw exception, so we serve a standard image
                raise cherrypy.HTTPRedirect(default_folder_image, 302)
        else:
            # no local album art found, online fetching deactivated, show default
            raise cherrypy.HTTPRedirect(default_folder_image, 302)
开发者ID:Isgar,项目名称:cherrymusic,代码行数:59,代码来源:httphandler.py

示例9: test_pathlib_compatibility

def test_pathlib_compatibility():
    try:
        import pathlib
    except ImportError:
        return
    testfile = next(iter(testfiles.keys()))
    filename = pathlib.Path(testfolder) / testfile
    tag = TinyTag.get(filename)
开发者ID:devsnd,项目名称:tinytag,代码行数:8,代码来源:test_all.py

示例10: get_node

def get_node(filename):
    from tinytag import TinyTag

    logger.debug(filename)
    try:
        tag = TinyTag.get(filename)
        logger.info(tag.title)
    except LookupError as err:
        logger.error("File `{0}` processing error: {1}".format(filename, err))
开发者ID:histrio,项目名称:rssutils,代码行数:9,代码来源:rssbook.py

示例11: __init__

	def __init__(self, ruta, titulo = "Cancion desconocida", artista = "Autor desconocido"):
		self.ruta = ruta
		datos = TinyTag.get(ruta)
		self.artista = artista
		self.titulo = titulo
		if datos.title:
			self.titulo = datos.title
		if datos.artist:
			self.artista = datos.artist
开发者ID:agusu,项目名称:TP3-Reproductor,代码行数:9,代码来源:cancion.py

示例12: genMoodHist

def genMoodHist(fileName, inputFile, outputFile, localOutput):
    countsR = initCounts()
    countsG = initCounts()
    countsB = initCounts()

    while True:
        byte = inputFile.read(3)
        if len(byte) == 3:
            countsR[int(ord(byte[0]) / 23)] += 1
            countsG[int(ord(byte[1]) / 23)] += 1
            countsB[int(ord(byte[2]) / 23)] += 1
        else:
            break

    for binIdx in range(12):
        xMin = binIdx * 23
        xMax = xMin + 22
        localOutput.write(str(xMin) + "-" + str(xMax) + ";")
    localOutput.write("\n")

    writeHist(countsR, localOutput)
    writeHist(countsG, localOutput)
    writeHist(countsB, localOutput)

    try:
        tag = TinyTag.get(fileName[:-5] + ".mp3")
        if tag.bitrate < 512:
            br = int(round(tag.bitrate))
        else:
            br = int(round(tag.bitrate/1000))

        outputFile.write(fileName + ";" +
                         str(br) + ";")

        table = []
        ct = 0;
        with open(fileName[:-5] + ".csv", 'r') as fd:
            for line in fd:
                table.append(line.strip().split(";"))
                ct += 1;
            for i in range(0,3):
                subtotal = float(0)
                for rgb in table:
                    subtotal += pow(int(rgb[i]), 2)
                subtotal /= ct
                outputFile.write(str(subtotal) + ";")

        outputFile.write(str(getCountsMax(countsR)) + ";" +
                         str(getCountsMax(countsG)) + ";" +
                         str(getCountsMax(countsB)) + "\n")

    except OSError as ose:
        print("Error: " + str(ose))
        return (1)

    return (0)
开发者ID:fhacktory,项目名称:Panda-Digger,代码行数:56,代码来源:moodHist.py

示例13: getTag

def getTag(song_path): #returns all matching fields
    tag = TinyTag.get(song_path)
    tag_fields = tag.__dict__
    details = {}
    for item in tag_fields:
        if item in fields and tag_fields[item] != None:
            details[item] = tag_fields[item]
    details['duration'] = "{:.2f}".format(details.get('duration'))
    if details.get('bitrate') > 5000:
        details.pop('bitrate')
    return details
开发者ID:broemere,项目名称:elitunes,代码行数:11,代码来源:musicdb.py

示例14: get_info

def get_info(testfile, expected):
    filename = os.path.join(samplefolder, testfile)
    print(filename)
    tag = TinyTag.get(filename)
    for key, value in expected.items():
        result = getattr(tag, key)
        fmt_string = 'field "%s": got %s (%s) expected %s (%s)!'
        fmt_values = (key, repr(result), type(result), repr(value), type(value))
        assert result == value, fmt_string % fmt_values
    print(tag)
    print(tag.__repr__())
开发者ID:rizumu,项目名称:tinytag,代码行数:11,代码来源:test.py

示例15: tags_wav

def tags_wav(name, infer=True):
    try:
        tags = TinyTag.get(name)
    except struct.error:
        if infer:
            uprint('WARN: Corrupted or mistagged, inferring artist and album: %s ...' % name, end=' ')
            return infer_album_artist(name)
        return None
    if not tags:
        return None, None
    return tags.artist, tags.album
开发者ID:khogeland,项目名称:liblinker,代码行数:11,代码来源:liblinker.py


注:本文中的tinytag.TinyTag类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。