• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python tinytag.TinyTag类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: get_artist

def get_artist(path):
    musicMeta = TinyTag.get(path)
    artist = musicMeta.artist
    
    if artist is not None:
        artist = ''.join(i for i in artist if i not in string.punctuation).replace(" ", "")
        
    if artist is None or not artist or artist.isspace():
        return "Unknown"
    else:
        return artist
开发者ID:maplerichie,项目名称:python,代码行数:11,代码来源:musicorganizer.py


示例17: __init__

 def __init__(self, title: str, filepath: str):
     super(SongModel, self).__init__()
     self.id = id(self)
     self.title = title
     self.filepath = filepath
     # This operation can go wrong when another program is using the filepath
     try:
         self._tags = TinyTag.get(self.filepath, False, True)
         self.duration = round(self._tags.duration)
     except PermissionError as e:
         self.duration = None
         print(e)
开发者ID:MelleDijkstra,项目名称:PythonMusicPlayer,代码行数:12,代码来源:models.py


示例18: moves_record

def moves_record():
    """-"""
    input_file = "../audio/show1/01_m.mp3"
    tag = TinyTag.get(input_file)
    track_length = tag.duration
    if os.path.exists(input_file + ".moves"):
        os.remove(input_file + ".moves")
    output_file = open(input_file + ".moves", "w")

    pygame.init()
    pygame.mixer.init()
    pygame.mixer.music.load(input_file)

    print "Playing " + input_file
    print "3... "
    time.sleep(1)
    print "2... "
    time.sleep(1)
    print "1... "
    time.sleep(1)

    pygame.mixer.music.play()
    start_time = time.time()
    last_time = 0
    is_done = False
    do_extra_close = False
    create_output(output_file, '{ "moveitem": [')
    while (is_done != True) and ((time.time() - start_time) < track_length):
        command = ""
        next_char = getch()
        current_time = time.time() - start_time
        if do_extra_close:
            create_output(
                output_file, str('   { "time":%.2f, "command":"%s" },' % ((current_time + last_time) / 2, "CLOSE"))
            )
            do_extra_close = False
        if next_char == "q":
            is_done = True
        else:
            if next_char == "i":  # This means OPEN_THEN_CLOSE
                command = "OPEN"
                do_extra_close = True
            if next_char == "o":
                command = "OPEN"
            if next_char == "p":
                command = "CLOSE"
            if command != "":
                create_output(output_file, str('   { "time":%.2f, "command":"%s" },' % (current_time, command)))
        last_time = current_time
    create_output(output_file, str('   { "time":%.2f, "command":"CLOSE" }\n] }' % track_length))
    output_file.close()
开发者ID:cberridge,项目名称:trappetroll,代码行数:51,代码来源:moves_record.py


示例19: copland_scrape

def copland_scrape():
    event_list = Event.objects.filter(start_date__gt=date(2013, 11, 22)).order_by('start_date')
    event_list = event_list.reverse()
    text_file = open("copland.txt", "w")
    fstring = ""
    for e in event_list:
	print(e.name)
        fstring += e.start_date.strftime("%m.%d.%y") + ": " + e.name
        program = Program.objects.select_related().filter(event = e).order_by('position')
        performers = Performer.objects.select_related().filter(event = e).order_by('position')
        recs = EventAudioRecording.objects.select_related().filter(event = e).order_by('position')
        dur = ""
	for i in range(len(program)):
            work = program[i].works.all()[0]
            if len(recs) > 0 and os.path.isfile(recs[i].compressed_master_recording.path):
                #mf = mad.MadFile(recs[i].compressed_master_recording.path)
                #dur = int(mf.total_time() / 1000)
                #dur = str(timedelta(seconds=dur))
		#fname = recs[i].uncompressed_master_recording.path
		#print(fname)
		#with contextlib.closing(wave.open(fname,'r')) as f:
		#    frames = f.getnframes()
    		#    rate = f.getframerate()
    		#    duration = math.floor(frames / float(rate))
		#    minutes, seconds = divmod(duration, 60)
		#    hours, minutes = divmod(minutes, 60)
		#    dur = str(hours) + ":" + str(minutes) + ":" + str(seconds)
		tag = TinyTag.get(recs[i].compressed_master_recording.path)
		duration = tag.duration
		print(duration)
		minutes, seconds = divmod(duration, 60)
                hours, minutes = divmod(minutes, 60)
                dur = str(int(hours)) + ":" + str(int(minutes)) + ":" + str(int(seconds))

            else:
                dur = "????"
            fstring += "\n"+work.name + " by " + work.authors.all()[0].name + "* - " + dur
        if len(performers) > 0:
            fstring += "\nperformers: "
            for p in performers:
                fstring += p.performer.name + " - "
                for i in p.instruments.all():
                    fstring += i.name + ", "
                fstring = fstring[:-2]
                fstring += "; "
            fstring = fstring[:-2]
        fstring += "\n\n"
    text_file.write(fstring.encode('utf-8'))
    text_file.close()
开发者ID:the-wulf,项目名称:thewulf-webapp,代码行数:49,代码来源:Copland_Scrape.py


示例20: get_encode_task

def get_encode_task(source_file, destination, bitrate):
    tags = TinyTag.get(source_file)
    track_relative_path = get_track_relative_path(tags)

    if track_relative_path:
        track_absolute_path = os.path.join(destination, track_relative_path)
        if not os.path.exists(track_absolute_path):
            return {
                'source': source_file,
                'destination': track_absolute_path,
                'destination_rel': track_relative_path,
                'bitrate': bitrate
            }
    else:
        print('Ignoring ' + source_file)
开发者ID:fxleblanc,项目名称:overseer,代码行数:15,代码来源:overseer.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python log.log_error函数代码示例发布时间:2022-05-27
下一篇:
Python orm.SessionFactory类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap