本文整理汇总了Python中stagger.read_tag函数的典型用法代码示例。如果您正苦于以下问题:Python read_tag函数的具体用法?Python read_tag怎么用?Python read_tag使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了read_tag函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: testID3v2ExtendedHeader
def testID3v2ExtendedHeader(self):
# First sample simply includes an empty extended header.
tag1 = stagger.read_tag(os.path.join(sample_dir,
"23.synthetic.empty-extended-header.lossy.id3"))
self.assertEqual(tag1.title, "The Millionaire's Holiday")
self.assertEqual(tag1.album, "Best Of Combustible Edison")
self.assertEqual(tag1.date, "1997")
self.assertEqual(tag1.track, 1)
self.assertEqual(tag1.genre, "Foobar")
self.assertEqual(tag1.artist, "Combustible Edison")
self.assertEqual(tag1.comment, " 0000132D 0000132D 00002FF0")
self.assertEqual(tag1.flags, { "extended_header" })
# Second sample file has an (invalid) CRC32 number in its extended header.
tag2 = stagger.read_tag(os.path.join(sample_dir,
"23.synthetic.extended-header-bad-crc.lossy.id3"))
self.assertEqual(tag2.title, "The Millionaire's Holiday")
self.assertEqual(tag2.album, "Best Of Combustible Edison")
self.assertEqual(tag2.date, "1997")
self.assertEqual(tag2.track, 1)
self.assertEqual(tag2.genre, "Foobar")
self.assertEqual(tag2.artist, "Combustible Edison")
self.assertEqual(tag2.comment, " 0000132D 0000132D 00002FF0")
self.assertEqual(tag2.flags, { "ext:crc_present", "extended_header" })
self.assertEqual(tag2.crc32, 0x20202020)
开发者ID:Rasor1911,项目名称:stagger,代码行数:25,代码来源:samples.py
示例2: addID3
def addID3(self, title, title2, artist):
print("Tagging "+"{0}.mp3".format(title))
try:
t = stagger.read_tag("{0}.mp3".format(title))
except:
# Try to add an empty ID3 header.
# As long stagger crashes when there's no header, use this hack.
# ID3v2 infos : http://id3.org/id3v2-00
m = open("{0}.mp3".format(title), 'r+b')
old = m.read()
m.seek(0)
m.write(b"\x49\x44\x33\x02\x00\x00\x00\x00\x00\x00" + old) # Meh...
m.close
# Let's try again...
try:
t = stagger.read_tag("{0}.mp3".format(title))
# Slicing is to get the whole track name
# because SoundCloud titles usually have
# a dash between the artist and some name
split = title2.find("-")
if not split == -1:
t.title = title2[(split + 2):]
t.artist = title2[:split]
else:
t.title = title2
t.artist = artist
t.write()
except:
print("[Warning] Can't add tags, skipped.")
开发者ID:Difegue,项目名称:UnlimitedGrooveWorks,代码行数:29,代码来源:soundclouDL.py
示例3: get_ID3_tags
def get_ID3_tags(self, album, file_path):
try:
album.artist = stagger.read_tag(file_path).artist
album.title = stagger.read_tag(file_path).album
if not album.artist or not album.title:
return None
return True
except stagger.errors.NoTagError:
return None
开发者ID:thesnapdragon,项目名称:music-seeker,代码行数:9,代码来源:file_scanner.py
示例4: test_write_id3
def test_write_id3(self):
""" Test write id3 tags """
sandbox = os.path.dirname(os.path.realpath(__file__)) + "/sandbox/"
sample = os.path.dirname(os.path.realpath(__file__)) + "/samples/"
filename = "92583301-dem-beats-3.mp3"
if not os.path.exists(sandbox):
os.mkdir(sandbox)
shutil.copyfile(sample + filename, sandbox + filename)
tag = stag()
tag._process_artwork_tmpfile = Mock(return_value=False)
client = Mock()
track = strack(json_obj[0], client=client)
tag.load_id3(track)
tag.write_id3(sandbox + filename)
res = stagger.read_tag(sandbox + filename)
self.assertEqual("Some text", res[TIT1].text[0])
self.assertEqual("Foo", res[TIT2].text[0])
self.assertEqual("dubstep bass", res[TIT3].text[0])
self.assertEqual("247010", res[TLEN].text[0])
self.assertEqual("foo", res[TOFN].text[0])
self.assertEqual("Dubstep", res[TCON].text[0])
self.assertEqual("free", res[TCOP].text[0])
self.assertEqual("1387373820", res[TDOR].text[0])
self.assertEqual("https://foobar.dev/1337", res[WOAS].url)
self.assertEqual("https://api.foobar.dev/1337", res[WOAF].url)
self.assertEqual("user1", res[TPUB].text[0])
self.assertEqual("http://user1.dev", res[WOAR][0].url)
self.assertEqual("User 1", res[TPE1].text[0])
self.assertEqual("User 1 Soundcloud tracks", res[TALB].text[0])
shutil.rmtree(sandbox)
开发者ID:williamurbano,项目名称:soundcloud-syncer,代码行数:35,代码来源:test_strack.py
示例5: copySongs
def copySongs(source,target):
windows = True
win = "\\"
lin = "/"
os.chdir(source)
a = [ name for name in os.listdir(os.getcwd()) if os.path.isdir(os.path.join(os.getcwd(), name)) ]
for x in a:
os.chdir(source)
os.chdir(x)
b = [ name for name in os.listdir(os.getcwd()) if os.path.isfile(os.path.join(os.getcwd(), name)) ]
for y in b:
os.chdir(source)
os.chdir(x)
oldfilename = os.getcwd()+"\\"+y
try:
tag = stagger.read_tag(y)
title = removeSymbols(tag.title.strip())
artist = removeSymbols(tag.artist.strip())
trackNr = tag.track
album = removeSymbols(tag.album.strip())
filename = str(trackNr)+" - "+title+".mp3"
except:
title = y
artist = "NO ID3 TAG"
trackNr = random.randint(0, 20)
album = "NoAlbum"
filename = str(trackNr)+" - "+title
if len(album) > 0:
if windows:
fullpath = target+win+artist+win+album+win
else:
fullpath = target+lin+artist+lin+album+lin
else:
if windows:
fullpath = target+win+artist+win+"NoAlbum"+win
else:
fullpath = target+lin+artist+lin+"NoAlbum"+lin
fullfilepath = fullpath+filename
if os.path.exists(r''+fullfilepath+''):
pass
else:
if windows:
if os.path.exists(r''+target+win+artist):
os.chdir(r''+target+win+artist)
else:
os.mkdir(r''+target+win+artist)
os.chdir(r''+target+win+artist)
else:
if os.path.exists(r''+target+lin+artist):
os.chdir(r''+target+lin+artist)
else:
os.mkdir(r''+target+lin+artist)
os.chdir(r''+target+lin+artist)
if os.path.exists(r''+fullpath):
os.chdir(r''+fullpath)
else:
os.mkdir(r''+fullpath)
os.chdir(r''+fullpath)
print(fullfilepath)
shutil.copyfile(r''+oldfilename+'', r''+fullfilepath+'')
开发者ID:pdarkness,项目名称:ipodcopy_python,代码行数:60,代码来源:ipodCopy.py
示例6: add_location
def add_location(location):
entry = {}
entry['location'] = location
entry['encoding'] = encoding.from_file(location.encode('utf-8')).decode('utf-8')
entry['mime'] = mime.from_file(location.encode('utf-8')).decode('utf-8')
if os.path.isdir(location):
entry['type'] = 'folder'
elif os.path.isfile(location):
entry['type'] = 'file'
(root, ext) = os.path.splitext(location)
if ext:
entry['extension'] = ext[1:]
if ext[1:].lower() == 'mp3':
print(location)
tag = stagger.read_tag(location)
for t in tag.values():
print(t)
print(tag.title)
print(tag.comment)
'''
try:
tag = stagger.read_tag(location)
for t in tag.values():
print(t)
print(t.comment)
except:
# No tag:w
pass
'''
sys.exit()
开发者ID:lhl,项目名称:songclub,代码行数:31,代码来源:crawl.py
示例7: db_insert_file
def db_insert_file(filename, file):
"""Reads file metadata and inserts it into the database."""
id3_file = None
try:
id3_file = read_tag(path.join(app.config["UPLOAD_FOLDER"], filename))
except NoTagError:
# No ID3 tags whatsoever
print("Inserting misc file: " + filename)
query = "INSERT IGNORE INTO ytfs_meta (filename) VALUES ('{0}');".format(filename)
cursor.execute(query)
db.commit()
return
track = id3_file.track if id3_file.track is not None else 0
title = id3_file.title.replace("'", "\\'")
artist = id3_file.artist.replace("'", "\\'")
album = id3_file.album.replace("'", "\\'")
year = id3_file.date.replace("'", "\\'")
genre = id3_file.genre.replace("'", "\\'")
track_comment = id3_file.comment.replace("'", "\\'")
print("Inserting: " + artist + " - " + title)
query = "INSERT IGNORE INTO ytfs_meta (filename, track, title, artist, album, year, genre, track_comment) " + \
"VALUES ('{0}', {1}, '{2}', '{3}', '{4}', '{5}', '{6}', '{7}');".format( \
filename, track, title, artist, album, year, genre, track_comment
)
cursor.execute(query)
db.commit() # Save changes back to DB
开发者ID:OzuYatamutsu,项目名称:flask-id3-file-store,代码行数:30,代码来源:server.py
示例8: load_id3
def load_id3(path):
data = {}
keys = ['album', 'album_artist', 'artist', 'composer', 'genre',
'sort_album', 'sort_album_artist', 'sort_artist',
'sort_composer', 'sort_title', 'title',
'track_total', 'date'
]
multikeys = {
'album': 'albums',
'album_artist': 'artists',
'artist': 'artists',
'composer': 'composers',
'genre': 'genres',
'sort_album': 'albums',
'sort_album_artist': 'artists',
'sort_artist': 'artists',
'sort_composer': 'composers'
}
tag = stagger.read_tag(path)
for key in keys:
if not hasattr(tag, key):
continue
obj = getattr(tag, key)
if isinstance(obj, Number) or \
(isinstance(obj, str) and \
len(obj) > 0):
data[key] = obj
if key in multikeys:
mkey = multikeys[key]
if mkey not in data:
data[mkey] = []
if obj not in data[mkey]:
data[mkey].append(obj)
return data
开发者ID:jadedgnome,项目名称:medialinkfs,代码行数:34,代码来源:id3.py
示例9: get
def get(self, track_id):
self.set_header("Content-Type", "application/json")
filepath = library[int(track_id)]["filepath"]
tag = stagger.read_tag(filepath)
ret_obj = {}
ret_obj["artist"] = tag.artist
# if 'APIC' in tag._frames:
# apic_frame = tag._frames['APIC']
# ret_obj["albumart"] = []
# for art in apic_frame:
# m = hashlib.md5()
# m.update(art.data)
# hashdata = m.digest()
# hash = base64.b16encode(hashdata).decode("ASCII")
# if not hash in image_dict:
# image_dict[hash] = {
# "mimetype": art.mime,
# "data": art.data
# }
# ret_obj["albumart"].append(hash)
self.write(json.dumps(ret_obj))
开发者ID:raiker,项目名称:Astarael,代码行数:29,代码来源:server.py
示例10: scan_path
def scan_path(session, not_found, path):
url = urlunparse(('file', '', path, '', '', ''))
if url in not_found:
del not_found[url]
return
LOG.debug('Scanning {0}.'.format(path))
try:
tag = read_tag(path)
if not (tag and tag.artist and tag.title):
LOG.warn('No ID3 for {0}.'.format(path))
return
try:
artist = session.query(LocalArtist).filter(LocalArtist.name == tag.artist).one()
except NoResultFound:
artist = LocalArtist(name=tag.artist)
session.add(artist)
track = LocalTrack(url=url, name=tag.title, local_artist=artist)
session.add(track)
session.commit()
except UnicodeEncodeError as e:
LOG.warn('Cannot encode ID3 for {0} ({1}).'.format(path, e))
session.rollback()
except NoTagError as e:
LOG.warn('Cannot read ID3 for {0} ({1}).'.format(path, e))
except ValueError as e:
LOG.warn('Cannot read ID3 for {0} ({1}).'.format(path, e))
开发者ID:Robbt,项目名称:uykfe,代码行数:26,代码来源:scan_mp3s.py
示例11: writeTag
def writeTag(file, songartist, song, show):
"write tag info. for some reason this won't work as root"
tag = stagger.read_tag(file)
tag.title = song
tag.artist = songartist
tag.album = show
tag.write()
开发者ID:guga31bb,项目名称:Python-Music-Copier,代码行数:7,代码来源:asotcopy.py
示例12: process_file
def process_file(self, f):
track = stagger.read_tag(f)
self._titles.append(Title(track.title, track.artist,
1,#track[TLEN].text[0],
f, int(track[TBPM].text[0]),
track[TKEY].text[0],
track.genre))
开发者ID:schroeder-,项目名称:musik_sorter,代码行数:7,代码来源:scanner.py
示例13: sortFile
def sortFile(name, root, dirs):
sFile = NewFile(name)
sFile.root = root
sFile.path = os.path.join(root, name)
if sFile.root != fromLocation:
sFile.baselevel = False
# set the type of file
if sFile.name.endswith(videoFileExt):
sFile.type = "video"
elif sFile.name.endswith(musicFileExt):
sFile.type = "music"
elif sFile.name.endswith(imageFileExt):
sFile.type = "image"
else:
sFile.type = "NA"
if sFile.type == "video":
# only care about season info if its a video
for list in fileSeason:
regex = re.compile(list)
list2 = regex.findall(name)
for l in list2:
if l != "":
sFile.l1 = l
sFile.hasseason = True
if len(sFile.l1) == 6:
sFile.seasonnum = int(sFile.l1[1:3])
if len(sFile.l1) == 4:
sFile.seasonnum = int(sFile.l1[1:2])
if sFile.type == "video":
if sFile.hasseason == True:
# shows
# find Show Folder
tmpPath = findFolder("folder", sFile.name, showFolder.path, str(sFile.seasonnum))
if sFile.seasonnum != 0:
# find season Folder
tmpPath = findFolder("season", str(sFile.seasonnum), tmpPath, str(sFile.seasonnum))
sFile.moveto = tmpPath
else:
# Movies
sFile.moveto = movieFolder.path
elif sFile.type == "image":
sFile.moveto = picFolder.path
elif sFile.type == "music":
tmpPath = ""
audiofile = stagger.read_tag(sFile.path)
tmpPath = findFolder("folder", audiofile.artist, musicFolder.path, "")
tmpPath = findFolder("folder", audiofile.album, tmpPath, "")
sFile.moveto = tmpPath
if sFile.moveto != "":
writeReport( sFile.path + " was moved to " + sFile.moveto + "\\" + sFile.name + "\n")
if not os.path.exists(sFile.moveto + "\\" + sFile.name):
shutil.copy(sFile.path, sFile.moveto + "\\" + sFile.name)
with printLock:
print(sFile.name)
开发者ID:tpenny35,项目名称:Python-Programs,代码行数:58,代码来源:TM.py
示例14: tagPath
def tagPath(mp3s):
"""Return a path built from the tags of the given mp3 files."""
tagPaths = []
for mp3 in mp3s:
tag = stagger.read_tag(mp3)
tagPaths.append(os.path.join(tag.artist, tag.album,
" ".join(["{0:02d}".format(tag.track), tag.title])
))
return tagPaths
开发者ID:tlvince,项目名称:scripts-python,代码行数:9,代码来源:organise.py
示例15: tag
def tag(self, music_file: DownloadedMusicFile):
tags = self.__parse_tags(music_file)
audio_tags = stagger.read_tag(music_file.file_mp3)
audio_tags.album = tags.album
audio_tags.artist = tags.artist
audio_tags.title = tags.title
audio_tags.picture = tags.file_thumbnail
audio_tags.write()
开发者ID:vl0w,项目名称:yt-mp3,代码行数:9,代码来源:tagger.py
示例16: GetSongInfo
def GetSongInfo(filename):
try:
tag = stagger.read_tag(filename)
except:
return None
else:
ret = "" + tag.title + "\n"
ret += "*" + tag.artist + "*\n"
ret += "*" + tag.album + "*"
return ret
开发者ID:halbrd,项目名称:Lemmy,代码行数:10,代码来源:LemmyRadio.py
示例17: scan
def scan(basepath, logfunc):
file_matcher = re.compile(r".*\.(mp3)")
image_dict = {}
tracks = []
i = 0
for dirpath, dirnames, filenames in os.walk(basepath):
for filename in filenames:
if file_matcher.match(filename):
filepath = os.path.join(dirpath, filename)
try:
tag = stagger.read_tag(filepath)
albumart = {}
if 'APIC' in tag._frames:
apic_frame = tag._frames['APIC']
for art in apic_frame:
m = hashlib.md5()
m.update(art.data)
hashdata = m.digest()
hash = base64.b16encode(hashdata).decode("ASCII")
if not hash in image_dict:
image_dict[hash] = {
"mimetype": art.mime,
"data": art.data
}
albumart[art.type] = hash
tracks.append({
"index": i,
"title": tag.title,
"track": tag.track,
"artist": tag.artist,
"album": tag.album,
"disc": tag.disc if tag.disc > 0 else 1,
"album_artist": tag.album_artist if tag.album_artist != "" else tag.artist,
"date": tag.date,
"filepath": filepath,
"album_art": albumart
})
i = i + 1
if i % 100 == 0:
logfunc("{0} tracks".format(i))
except stagger.errors.NoTagError as err:
logfunc("No tag found in {0}".format(filepath))
logfunc("Scan complete - {0} tracks found".format(i))
return (tracks, image_dict)
开发者ID:raiker,项目名称:Astarael,代码行数:55,代码来源:scanner.py
示例18: testFrameOrder
def testFrameOrder(self):
# 24.stagger.sample-01.id3 contains a simple test tag that has file frames
# in the following order:
#
# TIT2("TIT2"), TPE1("TPE1"), TALB("TALB"), TRCK("TRCK"), TPE2("TPE2")
testfile = os.path.join(os.path.dirname(__file__), "samples",
"24.stagger.sample-01.id3")
framelist = [TRCK, TPE2, TALB, TIT2, TPE1]
# Read tag, verify frame ordering is preserved
tag = stagger.read_tag(testfile)
self.assertEqual(len(tag), 5)
self.assertEqual(
set(tag.keys()), set(frame.frameid for frame in framelist))
self.assertEqual([frame.frameid for frame in tag.frames(orig_order=True)],
[frame.frameid for frame in framelist])
# Test frame contents
for framecls in framelist:
# tag[TIT2] == tag["TIT2"]
self.assertTrue(framecls in tag)
self.assertTrue(framecls.frameid in tag)
self.assertEqual(tag[framecls], tag[framecls.frameid])
# type(tag[TIT2]) == TIT2
self.assertTrue(isinstance(tag[framecls], framecls))
# Each frame contains a single string, which is the frame id in
# lowercase.
self.assertEqual(len(tag[framecls].text), 1)
self.assertEqual(tag[framecls].text[0], framecls.frameid.lower())
# Encode tag with default frame ordering, verify result is different.
with open(testfile, "rb") as file:
filedata = file.read()
tag.padding_max = 0
# Default sorting order is different.
tagdata = tag.encode()
self.assertEqual(len(tagdata), len(filedata))
self.assertFalse(tagdata == filedata)
# Override the sort order with an empty list,
# verify resulting order is the same as in the original file.
tag.frame_order = stagger.tags.FrameOrder()
tagdata = tag.encode()
self.assertTrue(tagdata == filedata)
tag2 = stagger.decode_tag(tagdata)
self.assertTrue(tag == tag2)
开发者ID:ajduncan,项目名称:stagger,代码行数:54,代码来源:tag.py
示例19: main
def main(args=sys.argv[1:]):
fpath = args[0]
# stagger.read_tag関数でmp3ファイルタグから情報を読み込む
tag = stagger.read_tag(fpath)
print(tag)
print(tag.title)
print(tag.album)
开发者ID:ekazyam,项目名称:Study,代码行数:11,代码来源:pp_330_stagger.py
示例20: next_song
def next_song():
global sid,ignition,playround,dbfile,aux,title,album,artist
if(aux==1):
return()
if(ignition == 2):
filename=get_next_offline_song()
else:
check_playround() # Check if playround ends
db = sqlite3.connect(dbfile) # Load database
cursor=db.cursor()
cursor.execute("SELECT sid,filename FROM `songs` \
LEFT JOIN (SELECT * FROM disabled_songs WHERE mode="+str(mode)+") AS d USING(sid) \
WHERE mode is null \
AND playround < "+str(playround)+" \
ORDER BY listened,skipped,RANDOM() \
LIMIT 1;")
try:
song=cursor.fetchone()
sid=song[0]
except TypeError:
print("Error while fetching song from DB")
skip_song()
return()
cursor.execute("UPDATE songs SET playround="+str(playround)+" WHERE sid="+str(sid)+";")
db.commit()
filename=song[1]
cursor.close();
db.close() # Close DB
print("Song: "+filename+"(SID:"+str(sid)+")")
if not os.path.isfile(filename):
print("File not found!")
skip_song()
pygame.mixer.music.set_volume(1)
try:
pygame.mixer.music.load(filename)
except:
print("Unable to play "+filename)
time.sleep(0.1)
return()
pygame.mixer.music.play()
try:
id3=stagger.read_tag(filename)
title=id3.title
album=id3.album
artist=id3.artist
except:
title=os.path.basename(filename)
artist=""
album=""
print("title: "+title)
print("album: "+album)
print("artist: "+artist)
print("playing:"+filename)
update_display()
开发者ID:Trueffelwurm,项目名称:MPi3,代码行数:54,代码来源:MPi3.py
注:本文中的stagger.read_tag函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论