How to use the mutagen.easyid3.EasyID3 function in mutagen

To help you get started, we’ve selected a few mutagen examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github quodlibet / mutagen / tests / test_easyid3.py View on Github external
def test_write_original_date_double(self):
        self.id3["originaldate"] = ["2004", "2005"]
        self.id3.save(self.filename)
        id3 = EasyID3(self.filename)
        self.failUnlessEqual(id3["originaldate"], ["2004", "2005"])

        self.id3["originaldate"] = ["2004", "2005"]
        self.id3.save(self.filename)
        id3 = EasyID3(self.filename)
        self.failUnlessEqual(id3["originaldate"], ["2004", "2005"])
github quodlibet / mutagen / tests / test_easyid3.py View on Github external
def test_txxx_latin_first_then_non_latin(self):
        self.id3["performer"] = [u"foo"]
        self.id3["performer"] = [u"\u0243"]
        self.id3.save(self.filename)
        new = EasyID3(self.filename)
        self.assertEqual(new["performer"], [u"\u0243"])
github jmeb / symmusic / symmusic.py View on Github external
if os.name is not 'posix':
    print 'Symmusic requires a posix environment!'
    sys.exit()

  #Check that dst isn't inside src
  if os.path.commonprefix([src, dst]) is src:
    print 'Destination is inside source. This is not good. Failing!'
    sys.exit()

  #Set hours to 0 if not set so we can pass hours variable
  if not hours:
    hours = 0

  #This is ugly...but there aren't many formats, and it is easy.
  if 'mp3' in formats:
    mp3 = [ getMusic(src,".mp3"), EasyID3, '.mp3' ]
    mp3fails = theWholeEnchilada(mp3,dirs,names,dst,hours)

  if 'flac' in formats:
    flac = [ getMusic(src,".flac"), FLAC, '.flac' ]
    flacfails = theWholeEnchilada(flac,dirs,names,dst,hours)

  if 'ogg' in formats:
    ogg = [ getMusic(src,".ogg"), OggVorbis, '.ogg' ]
    oggfails = theWholeEnchilada(ogg,dirs,names,dst,hours)

  #Print failed lists for redirection
  if verbose is True:
    print '\n' + "FAILURES:" + '\n'
    print mp3fails, flacfails, oggfails

  #Clean out small directories
github simon-weber / gmusicapi / gmusicapi / protocol.py View on Github external
filemap = {} #map clientid -> filename

        metadata = self.make_pb("metadata_request")

        for filename in filenames:

            if not filename.split(".")[-1].lower() == "mp3":
                LogController.get_logger("make_metadata_request").error(
                        "cannot upload '%s' because it is not an mp3.", filename)
                continue

            track = metadata.tracks.add()

            #Eventually pull this to supported_filetypes
            audio = MP3(filename, ID3 = EasyID3)


            #The id is a 22 char hash of the file. It is found by:
            # stripping tags
            # getting an md5 sum
            # converting sum to base64
            # removing trailing ===

            #My implementation is _not_ the same hash the music manager will send;
            # they strip tags first. But files are differentiated across accounts,
            # so this shouldn't cause problems.

            #This will reupload files if their tags change.
            
            with open(filename, mode="rb") as f:
                file_contents = f.read()
github dato / minirok / minirok / tag_reader.py View on Github external
"""Return a dict with the tags read from the given path.

        Tags that will be read: Track, Artist, Album, Title, Length. Any of
        these may be missing in the returned dict.
        """
        try:
            info = mutagen.File(path)
            if isinstance(info, mutagen.mp3.MP3):
                # We really want an EasyID3 object, so we re-read the tags now.
                # Alas, EasyID3 does not include the .info part, which contains
                # the length, so we save it from the MP3 object.
                dot_info = info.info
                try:
                    info = mutagen.easyid3.EasyID3(path)
                except mutagen.id3.ID3NoHeaderError:
                    info = mutagen.easyid3.EasyID3()
                info.info = dot_info
            elif info is None:
                minirok.logger.warning(
                    'could not read tags from %s: mutagen.File() returned None',
                    path)
                return {}
        except Exception, e:
            if path in str(e):  # Mutagen included the path in the exception.
                msg = 'could not read tags: %s' % e
            else:
                msg = 'could not read tags from %s: %s' % (path, e)
            minirok.logger.warning(msg)
            return {}

        tags = {}
github Mechazawa / REDBetter-crawler / tagging.py View on Github external
totaldiscs = scrub_tag('disctotal', flac_info['disctotal'][0])

            if totaldiscs:
                transcode_info['discnumber'] = [u'%s/%s' % (transcode_info['discnumber'][0], totaldiscs)]

    transcode_info.save()

# EasyID3 extensions for redactedbetter.

for key, frameid in {
    'albumartist': 'TPE2',
    'album artist': 'TPE2',
    'grouping': 'TIT1',
    'content group': 'TIT1',
    }.iteritems():
    EasyID3.RegisterTextKey(key, frameid)

def comment_get(id3, _):
    return [comment.text for comment in id3['COMM'].text]

def comment_set(id3, _, value):
    id3.add(mutagen.id3.COMM(encoding=3, lang='eng', desc='', text=value))

def originaldate_get(id3, _):
    return [stamp.text for stamp in id3['TDOR'].text]

def originaldate_set(id3, _, value):
    id3.add(mutagen.id3.TDOR(encoding=3, text=value))

EasyID3.RegisterKey('comment', comment_get, comment_set)
EasyID3.RegisterKey('description', comment_get, comment_set)
EasyID3.RegisterKey('originaldate', originaldate_get, originaldate_set)
github bamos / python-scripts / python2.7 / music-autoplaylists.py View on Github external
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--musicDir', type=str, default='.')
    parser.add_argument('--playlistDir', type=str, default='./playlists/auto')
    args = parser.parse_args()

    genres = defaultdict(list)
    for dpath, dnames, fnames in os.walk(args.musicDir):
        if '.git' in dpath:
            continue
        for fname in fnames:
            if os.path.splitext(fname)[1] != '.mp3':
                continue
            p = os.path.abspath(os.path.join(dpath, fname))
            audio = EasyID3(p)
            if 'genre' in audio:
                assert(len(audio['genre']) == 1)
                genre = toNeat(str(audio['genre'][0]))
            else:
                genre = 'Unknown'
            genres[genre].append(p)

    if os.path.exists(args.playlistDir):
        shutil.rmtree(args.playlistDir)
    os.makedirs(args.playlistDir)

    for genre, songs in genres.items():
        p = os.path.join(args.playlistDir, genre + '.m3u')
        print("Creating playlist: {}".format(p))
        with open(p, 'w') as f:
            f.write("#EXTM3U\n")
github cmcginty / flacsync / flacsync / encoder.py View on Github external
:param tags: Source tag values from FLAC file.
      :type  tags: dict
      """
      mp3_fields = {
         'artist':tags['artist'],         'title':tags['title'],
         'album':tags['album'],           'date':tags['year'],
         'tracknumber':tags['track'],     'genre':tags['genre'],
         'discnumber':tags['disc'],       'composer':tags['composer'],
         'replaygain_track_gain':tags['rg_track_gain'],
         'replaygain_track_peak':tags['rg_track_peak'],
         'replaygain_album_gain':tags['rg_album_gain'],
         'replaygain_album_peak':tags['rg_album_peak'],
      }
      mp3_fields = dict((k,v) for k,v in mp3_fields.items() if v)
      # tag MP3 file
      audio = EasyID3(self.dst)
      for x,y in mp3_fields.items():
        audio[x] = y
      err = audio.save()
      return self._check_err( err, "MP3 tag failed:" )
github iTaybb / iQuality / code / GuiSubWindows / ID3Window.py View on Github external
mp3Obj.add_tags()
			mp3Obj.save()
		except error:
			pass
		except HeaderNotFoundError:
			log.warning("This MP3 files seems to be faulty. Cannot edit it's ID3 data. (Error: HeaderNotFoundError)")
			QtGui.QMessageBox.critical(self, tr("Error"), tr("This MP3 files seems to be faulty. Cannot edit it's ID3 data."), QtGui.QMessageBox.Ok)
			self.isValid = False
			return
		try:
			self.easyID3Obj = EasyID3(self.path)
			self.ID3Obj = ID3(self.path)
		except ID3NoHeaderError:
			# That means mp3Obj.add_tags() didn't work for a reason.
			utils.appendDummyID3(self.path)
			self.easyID3Obj = EasyID3(self.path)
			self.ID3Obj = ID3(self.path)

		USLT_Tag = [x for x in self.ID3Obj.keys() if x.startswith('USLT')]
		self.originalLyrics = self.ID3Obj[USLT_Tag[0]].text if USLT_Tag else ""
		
		APIC_Tag = [x for x in self.ID3Obj.keys() if x.startswith('APIC')]
		if APIC_Tag:
			APIC_Tag = APIC_Tag[0]
			
			mime = self.ID3Obj[APIC_Tag].mime
			if mime == u'image/jpeg':
				self.pix_path = os.path.join(config.temp_dir, 'album_art.jpg')
			elif mime == u'image/png':
				self.pix_path = os.path.join(config.temp_dir, 'album_art.png')
			else:
				self.pix_path = os.path.join(config.temp_dir, 'album_art.pic')
github foobnix / foobnix / src / foobnix / old / model / entity.py View on Github external
path = self.path.lower()

        if path.endswith(".flac"):
            try:
                audio = FLAC(self.path)
            except:
                return None

        elif path.endswith(".ape") or path.endswith(".mpc"):
            try:
                audio = APEv2(self.path)
            except:
                return None
        else:
            try:
                audio = MP3(self.path, ID3=EasyID3)
            except:
                return None


        artist = None
        title = None

        try:
            if audio and audio.has_key('artist'): artist = audio["artist"][0]
            if audio and audio.has_key('title'): title = audio["title"][0]
            if audio.info: self.info = audio.info.pprint()
            #if audio and audio.has_key('duration'): self.duration = audio["duration"][0]

            if artist and title:
                line = artist + " - " + title
                try: