def set_cover_art(self, track, local_filename): try: tag = eyeD3.Tag() if tag.link(local_filename): if 'APIC' in tag.frames and len(tag.frames['APIC']) > 0: apic = tag.frames['APIC'][0] extension = 'jpg' if apic.mimeType == 'image/png': extension = 'png' cover_filename = '%s.cover.%s' (local_filename, extension) cover_file = open(cover_filename, 'w') cover_file.write(apic.imageData) cover_file.close() gpod.itdb_track_set_thumbnails(track, cover_filename) return True except: log('Error getting cover using eyeD3', sender=self) try: cover_filename = os.path.join(os.path.dirname(local_filename), 'folder.jpg') if os.path.isfile(cover_filename): gpod.itdb_track_set_thumbnails(track, cover_filename) return True except: log('Error getting cover using channel cover', sender=self) return False
def main(argv): try: opts, args = getopt.getopt(argv, "ha:l:g:d", ["help", "artist=", "album=", "genre="]) except getopt.GetoptError: usage() sys.exit(2) for opt, arg in opts: if opt in ("-h", "--help"): usage() sys.exit() elif opt == '-d': global _debug _debug = 1 elif opt in ("-a", "--artist"): print("Found artist: ", arg) artist = arg elif opt in ("-l", "--album"): print("Found album: ", arg) album = arg elif opt in ("-g", "--genre"): print("Found genre: ", arg) genre = arg for file in args: print("file: ", file) tag = eyeD3.Tag() tag.link(file) printtag()
def convertDirMP3ToWav(dirName, Fs, nC, useMp3TagsAsName = False): ''' This function converts the MP3 files stored in a folder to WAV. If required, the output names of the WAV files are based on MP3 tags, otherwise the same names are used. ARGUMENTS: - dirName: the path of the folder where the MP3s are stored - Fs: the sampling rate of the generated WAV files - nC: the number of channesl of the generated WAV files - useMp3TagsAsName: True if the WAV filename is generated on MP3 tags ''' types = (dirName+os.sep+'*.mp3',) # the tuple of file types filesToProcess = [] tag = eyeD3.Tag() for files in types: filesToProcess.extend(glob.glob(files)) for f in filesToProcess: tag.link(f) if useMp3TagsAsName: artist = tag.getArtist() title = tag.getTitle() if len(title)>0 and len(artist)>0: wavFileName = ntpath.split(f)[0] + os.sep + artist.replace(","," ") + " --- " + title.replace(","," ") + ".wav" else: wavFileName = f.replace(".mp3",".wav") else: wavFileName = f.replace(".mp3",".wav") command = "avconv -i \"" + f + "\" -ar " +str(Fs) + " -ac " + str(nC) + " \"" + wavFileName + "\""; print command os.system(command.decode('unicode_escape').encode('ascii','ignore').replace("\0",""))
def id3v2_getval(mp3, tagstr): if type(tagstr) == tuple: tagstr = list(tagstr) tag = eyeD3.Tag() try: tag.link(mp3) except: #if we could not link to id3 return empty vals if type(tagstr) == list: return [''] * len(tagstr) else: os.sys.stderr.write('eyeD3 unable to link to file %s\n' % (mp3)) return '' if type(tagstr) == list: retval = list() for t in tagstr: try: val = id3v2_getval_sub(tag, t) except: os.sys.stderr.write( 'eyeD3 unable to read id3 tag(s) %s from file %s\n' % (str(tagstr), mp3)) val = '' retval.append(val) return retval else: #try : val = id3v2_getval_sub(tag, tagstr) #except : # val='' # os.sys.stderr.write('eyeD3 unable to read id3 tag %s from file %s\n' % (tagstr,mp3)) return val
def add_lyrics_from_string(self, MP3_file, lyrics): ''' Write lyrics string to mp3 file. @type MP3_file: string @type lyrics: string @param lyrics: song lyrics to be written @param MP3_file: name of MP3 file to write lyrics to @rtype boolean @return: true if modified, false if not ''' #print "DEBUG: %s" % type(lyrics) #lyrics = unicode(lyrics).encode('utf-8') #lyrics = lyrics.replace("\n", "") #print "DEBUG: %s" % type(lyrics) tag = eyeD3.Tag() tag.header.setVersion(eyeD3.ID3_V2_4) tag.encoding = "\x03" # set UTF-8 encoding tag.link(MP3_file) try: if self.__settings['force'] == True: tag.addLyrics(lyrics) tag.update() return True else: # test for existing lyrics before write existingTag = tag.getLyrics() if len(existingTag) == 0: # no lyric frames, so we can write tag.addLyrics(lyrics) tag.update() return True return False except: return False
def getAndSaveCoverartImage(self, srcfile, new_name): #srcfile = location.replace("\ "," ") dstfolder = os.path.dirname(self.save_path) #dstfile = self.save_path.replace(os.path.dirname(self.save_path)+"/","") tag = eyeD3.Tag() #print "src: %s, dstfolder: %s " % (srcfile, dstfolder ) if os.path.isfile(srcfile): #print "%s is file" % srcfile if os.path.splitext(srcfile)[1] == ".mp3": # Extract picture #print "% is mp3" try: tag.link(srcfile) for image in tag.getImages(): dstfile = "%s.JPEG" % new_name print "FILE %s: %s" % (self.song_counter, dstfile) image.writeFile(dstfolder, dstfile) self.song_counter = self.song_counter + 1 except: print "Unable to extract image for: " + srcfile #traceback.print_exc() else: print "ERROR: %s not found to be file" % srcfile
def find_song_(directory): directory = os.path.normpath(directory) + os.sep for song in os.listdir(directory): if os.path.isdir(os.path.join(directory, song)) or "mp3" not in song: pass else: tag = eyeD3.Tag() try: if tag.link(os.path.join(directory, song)): if tag.getArtist(): if not os.path.exists(directory + tag.getArtist()): os.mkdir(directory + tag.getArtist()) shutil.move(song, directory + tag.getArtist()) else: try: shutil.move(song, directory + tag.getArtist()) except: os.remove(os.path.join(directory, song)) else: if not os.path.exists(directory + unknow_artist_dir): os.mkdir(directory + unknow_artist_dir) shutil.move(song, directory + unknow_artist_dir) else: try: shutil.move(song, directory + unknow_artist_dir) except: os.remove(os.path.join(directory, song)) except: pass
def rename_id3(filename): if os.path.isfile(filename) == False: print "File not found: " + filename return print "Processing: " + filename tag = eyeD3.Tag() tag.link(filename) artist = tag.getArtist() if len(artist) == 0: artist = "unknown" title = tag.getTitle() if len(title) == 0: with open(filename) as inFile: d = hashlib.sha1() d.update(inFile.read()) digest = d.hexdigest() title = digest new_filename = artist + ' - ' + title + '.mp3' print "Renaming " + filename + " to " + new_filename os.rename(filename, new_filename) return
def store_new_mp3(self, mp3filename): """ Create a new instance for the Mp3 filename given into the mp3items dict. """ mp3_metadata = eyeD3.Mp3AudioFile(mp3filename) # If the file has no Tag... if not mp3_metadata.tag: APPLOG.warning("MP3 File has no Tag, creating a new one") tag = eyeD3.Tag() tag.setVersion(eyeD3.tag.ID3_DEFAULT_VERSION) tag.linkedFile = eyeD3.LinkedFile(mp3filename) mp3_metadata.tag = tag # Update to ID3_DEFAULT_VERSION if actual is under ID3_V2 # Specific update for the ID3_V2_2 tag version also, because the eyeD3 # raise TagException with "Unable to write ID3 v2.2". :( if mp3_metadata.tag.getVersion() <= eyeD3.tag.ID3_V2_2: APPLOG.warning("Updating ID3 tag %s to the eyeD3 ID3_DEFAULT_VERSION(%i)" %\ (mp3_metadata.tag.getVersionStr(), eyeD3.tag.ID3_DEFAULT_VERSION)) mp3_metadata.tag.setVersion(eyeD3.tag.ID3_DEFAULT_VERSION) # Assign metadata to the mp3 file self.mp3items[mp3filename] = {} self.mp3items[mp3filename]['metadata'] = mp3_metadata self.mp3items[mp3filename]['apic_pixbuf'] = self.extract_apic_pixbuf( mp3_metadata) self.mp3items[mp3filename]['rename_with'] = None
def awesome(username, themeId): # lookup sound for username usr = User.query.filter(User.uid == username).first() if usr is None: return "%s isn't registered to be AWESOME. :(" % username if themeId == "random": songs = glob.glob("%s/%s_theme_*.mp3" % (app.config['UPLOAD_FOLDER'], username)) mp3fname = choice(songs) else: mp3fname = os.path.join(app.config['UPLOAD_FOLDER'], "%s_theme_%s.mp3" % (username, themeId)) tag = eyeD3.Tag() tag.link(mp3fname) #print "calling mikehup mpg123 %s from %s &" % (mp3fname,os.getcwd()); #subprocess.call('mpg123 %s' % mp3fname, shell=True) if pygame.mixer.music.get_busy(): pygame.mixer.music.queue(mp3fname) else: pygame.mixer.music.load(mp3fname) pygame.mixer.music.play() #this breaks the queue, disable or now #pygame.mixer.music.set_endevent(MUSIC_END) return render_template('awesome.html', title=tag.getTitle(), uid=username)
def fix(fname): print fname tag = eyeD3.Tag() if not tag.link(fname): return print eyeD3.utils.versionToString(tag.header.version) if s_args: for s in s_args: s = s.split(':', 1) print u'Set %s: %s' % tuple(s) tag.frames.setTextFrame(str(s[0]), s[1], eyeD3.UTF_16_ENCODING) for frame in tag.frames: try: e = eyeD3.frames.id3EncodingToString(frame.encoding) u = frame.text except: continue if not isinstance(u, str) and not isinstance(u, unicode): continue if l_flag: print frame, u, pprint.pformat(u) if e == 'latin_1' and not RE_IS_LATIN.match(u): u = u.encode('latin_1').decode('shift_jis') print 'Recover:', u frame.text = u frame.encoding = eyeD3.UTF_16_ENCODING if w_flag: tag.update(eyeD3.ID3_V2_4) print
def mainfunc(pat): tag = eyeD3.Tag() for dpath, dnames, filenames in os.walk(pat): if not any(isaudio(filename) for filename in filenames): continue if any(isimage(filename) for filename in filenames): continue if noextract: print dpath continue madefile = False for f in (os.path.join(dpath, f) for f in filenames if isaudio(os.path.join(dpath, f))): tag.link(f) imgs = tag.getImages() if imgs == None or len(imgs) <= 0: continue imgs = imgs[0] imgs.writeFile(path=dpath, name="folder." + imgs.mimeType.split("/")[1].lower()) madefile = True break if not madefile: print dpath
def downloadFileWithPython(song_name, song_artist, song_link, song_type, write_tag, download_directory): if (write_tag): import eyeD3 tag = eyeD3.Tag() for i in range(len(song_name)): """Check None song_link when download.""" if song_link[i] is not None: media_filename = song_name[i].replace('/', '-') + " - " + \ song_artist[i].replace('/', '-') + '.' + \ song_type[i] media_filepath = os.path.join(download_directory, media_filename) print "Downloading %s - %s" % (song_artist[i], song_name[i]) urlretrieve(song_link[i], media_filepath) if (write_tag) and (song_type[i] == 'mp3'): tag.link(media_filepath) tag.setTitle(convert_to_ascii(song_name[i])) tag.setArtist(convert_to_ascii(song_artist[i])) tag.update() print "Done." else: print "Can't find media url for %s - %s " % (song_artist[i], song_name[i])
def downloadFileWithWget(song_name, song_artist, song_link, song_type, write_tag, download_directory): wget = ["wget", "-q", "-nd", "-np", "-c", "-r"] if (write_tag): import eyeD3 tag = eyeD3.Tag() for i in range(len(song_name)): """Check None song_link when download.""" if song_link[i] is not None: media_filename = song_name[i].replace('/', '') + " - " + \ song_artist[i].replace('/', '') + '.' + \ song_type[i] media_filepath = os.path.join(download_directory, media_filename) wget_args = [] wget_args.append(song_link[i]) wget_args.append('-O') wget_args.append(media_filepath) print "Downloading %s - %s" % (song_artist[i], song_name[i]) call(wget + wget_args) if (write_tag) and (song_type[i] == 'mp3'): tag.link(media_filepath) tag.setTitle(convert_to_ascii(song_name[i])) tag.setArtist(convert_to_ascii(song_artist[i])) tag.update() print "Done." else: print "Can't find media url for %s - %s " % (song_artist[i], song_name[i])
def getname(path): tag = eyeD3.Tag() tag.link(path) if tag.getAlbum() == "": Album = "Unknown Album" else: Album = tag.getAlbum() return Album
def __init__(self, mp3): self._eyeD3 = eyeD3.Tag() # file exists or readable? try: self._eyeD3.link(mp3) self.getFileInfo() except: print '读取文件错误'
def show_tempo(mp3): "given an mp3, print out the artist, title and tempo of the song" tag = eyeD3.Tag() tag.link(mp3) my_tempo = tempo.get_tempo(tag.getArtist(), tag.getTitle()) print 'File: ', mp3 print 'Artist:', tag.getArtist() print 'Title: ', tag.getTitle() print 'Tempo: ', my_tempo print
def get_meta(path): tag = eyeD3.Tag() tag.link(path) print "Artist: %s" % tag.getArtist() print "Album: %s" % tag.getAlbum() print "Track: %s" % tag.getTitle() TrackNum, TrackTotal = tag.getTrackNum() print "Track #: %d" % TrackNum print "Track TOtal: %d" % TrackTotal print "Release Year: %s" % tag.getYear()
def update_meta(path): tag = eyeD3.Tag() tag.link(path) tag.setArtist("ARTIST") tag.setTitle("TITLE") tag.setDate("2012") tag.setGenre("GENRE") tag.setAlbum("ALBUM") tag.setTrackNum((12, 12)) tag.update()
def add_tag(filename, tags): tag = eyeD3.Tag() tag.link(filename) tag.header.setVersion(eyeD3.ID3_ANY_VERSION) tag.setTextEncoding(eyeD3.UTF_8_ENCODING) tag.setTitle(tags['title']) tag.setAlbum(tags['albumtitle']) tag.setArtist(tags['artist']) tag.setDate(tags['public_time']) tag.addImage(eyeD3.frames.ImageFrame.FRONT_COVER, tags['picture_file']) tag.update()
def auto_set_tags(self): """ - create ID3tags if not exist - fill empty Artist, Album, Titel tags - set mp3 genre """ self.tag = eyeD3.Tag() try: has_tags = self.tag.link(self.path) except Exception, err: print "Can't eyeD3 link to MP3 file:", err return
def tag_mp3(fname, rec, comment): conn_logger.debug('tag mp3 %s' % fname) tag = eyeD3.Tag() tag.link(fname) tag.setTitle(rec.title) tag.setArtist(rec.performer_names) tag.addComment(comment) tag.update() conn_logger.info('tagged mp3 "%s"' % fname) return True
def tagToFilename(path): try: import eyeD3 tag = eyeD3.Tag() tag.link(path) artist = strToFilename(tag.getArtist()) title = strToFilename(tag.getTitle()) if artist == '' or title == '': return None newfn = '%s-%s.mp3' % (artist, title) return newfn except Exception, e: print 'error reading tag for %s: %s' % (path, e)
def processEntry(): tag = eyeD3.Tag() try: if not tag.link(fullpath): print "something wrong with file " + fullpath return except: print fullpath + ": error, may be tags corrupted" return newTitle = entry.partition('.')[0] tag.setTitle(newTitle) tag.update() printOutput("%s: updated, new title is %s" % (fullpath, newTitle))
def tagGet(self,path):#get music tags to load into music table taglist = [] tag = eyeD3.Tag() try:#to get music play duration trackInfo = eyeD3.Mp3AudioFile(path) Duration = trackInfo.getPlayTimeString() except: Duration = "Unknown" else: Duration = trackInfo.getPlayTimeString() tag.link(path) try:#get music genre g = tag.getGenre() except: Genre = "Unknown Genre"#tag.getGenre() else: if g == None: Genre = "Unknown Genre" else: junk = tag.getGenre() Genre = junk g = str(Genre) g = g.replace("(","") g = g.replace(")","") Genre = g.translate(None,digits) #get music arist, album, title, year tags if tag.getArtist() == "": Artist = "Unknown Artist" else: Artist = tag.getArtist() if tag.getAlbum() == "": Album = "Unknown Album" else: Album = tag.getAlbum() if tag.getTitle() == "": Title = self.titleResolve(path) else: Title = tag.getTitle() if tag.getYear() == None: Year = " " else: Year = tag.getYear() taglist.extend([Title,Artist,Album,Duration,Year,Genre]) return taglist
def tag_mp3(fname, rec, comment): conn_logger.info('tag mp3 %s' % fname) try: tag = eyeD3.Tag() tag.link(fname) tag.remove(eyeD3.ID3_ANY_VERSION) #tag.link(fname, eyeD3.ID3_V2) title = rec.title.encode('iso-8859-1', 'ignore') tag.setTitle(title) tag.setArtist(rec.performer_names) tag.addComment(comment) tag.update() except (ValueError, eyeD3.TagException), e: conn_logger.error('tag_mp3 failed: %s - %s' % (fname, str(e)))
def profile(username): u = User.query.filter(User.uid == username).first() if u: mp3s = sorted( glob.glob("%s/%s_theme_*" % (app.config['UPLOAD_FOLDER'], username))) #mp3fname = os.path.join(app.config['UPLOAD_FOLDER'], u.mp3) mp3list = [] for f in mp3s: tag = eyeD3.Tag() tag.link(f) mp3list.append([f, tag.getTitle()]) return render_template("profile.html", uid=u.uid, mp3s=mp3list) return "%s is not an awesome user" % username
def getTags(self, filename): tags = {} import eyeD3 tagMessage = "" try: id3info = eyeD3.Tag() id3info.link(filename) for tag in (AudioTags): if (tag == "track"): track = id3info.getTrackNum() if (track is not None): tags[tag] = track[0] elif (tag == "genre"): genre = None try: genre = id3info.getGenre() if (genre is not None): tags[tag] = genre.getName() else: tags[tag] = "unknown" except eyeD3.GenreException, ge: # Load genre string another way tf = id3info.frames[eyeD3.GENRE_FID] genre = tf[0].text if (genre is not None and genre != ""): tags["genre"] = genre else: tags["genre"] = "unknown" else: #print "GETTING",tag.title() getter = "get" + tag.title() #print "\t",getter func = getattr(id3info, getter) if (func is None): print "Huh - no func named", getter tags[tag] = func() #print "\tTag",tag,tags[tag],type(tags[tag]) hasTag = tags.has_key(tag) #and str(tags[tag]) != "" if (not hasTag and tag != "year"): tagMessage += "\tTag not set: " + tag + "\n" tags[tag] = self.formatTag(tags[tag]) # Was - tags[tag] = str(tags[tag]).encode("latin-1") #tags[tag] = tags[tag].encode("latin-1") except eyeD3.tag.TagException, t: print "Error processing tags for", filename, ":", t
def set_MP3_tags(self, file): ''' Reads and stores MP3 tags (artist, track, lyrics). @type file: string @param file: name of tagged MP3 file to read tags from ''' if eyeD3.isMp3File(file): tag = eyeD3.Tag() tag.link(file) self.artist = tag.getArtist(eyeD3.ARTIST_FID) self.track = tag.getTitle() self.lyrics = self.get_lyrics_from_tag(tag) self.album = tag.getAlbum() self.order_number = tag.getTrackNum()
def link_tag(_file): tag = eyeD3.Tag() v2_failed = False try: tag.link(_file, eyeD3.ID3_V2) if not (tag.getArtist() and tag.getTitle()): v2_failed = True except TagException: print 'warning: failed to load ID3_V2 tag' traceback.print_exc(file=sys.stdout) v2_failed = True if v2_failed: tag.link(_file, eyeD3.ID3_V1) return tag