コード例 #1
0
def _audio_tcom(atuple):
    audio, atag, advanced, _, _ = atuple
    if advanced:
        param = ast.literal_eval(atag)
        audio.add(TCOM(3, param[1]))
    else:
        audio.add(TCOM(3, atag))
コード例 #2
0
    def _add_metadata(self, show, file_name):
        if file_name is None:
            raise "file_name is not set - you cannot add metadata to None"

        config = Configuration()

        time_string = format_date(config.date_pattern,
                                  time.localtime(self.start_time))
        comment = config.comment_pattern % {
            'show': show.name,
            'date': time_string,
            'year': time.strftime('%Y', time.gmtime()),
            'station': show.station.name,
            'link_url': show.get_link_url()
        }

        audio = ID3()
        # See http://www.id3.org/id3v2.3.0 for details about the ID3 tags

        audio.add(TIT2(encoding=2, text=["%s, %s" % (show.name, time_string)]))
        audio.add(
            TDRC(encoding=2,
                 text=[format_date('%Y-%m-%d %H:%M', self.start_time)]))
        audio.add(TCON(encoding=2, text=[u'Podcast']))
        audio.add(TALB(encoding=2, text=[show.name]))
        audio.add(TLEN(encoding=2, text=[show.duration * 1000]))
        audio.add(TPE1(encoding=2, text=[show.station.name]))
        audio.add(TCOP(encoding=2, text=[show.station.name]))
        audio.add(COMM(encoding=2, lang='eng', desc='desc', text=comment))
        audio.add(TCOM(encoding=2, text=[show.get_link_url()]))
        self._add_logo(show, audio)
        audio.save(file_name)
コード例 #3
0
    def write_id3_tags(self, file_name):
        """Writes ID3 tags from out music file into given MP3 file

        Args:
            :file_name
        """
        try:
            tags = ID3(file_name)
        except ID3NoHeaderError:
            # Adding ID3 header
            tags = ID3()

        tags[self.TAG_TITLE] = TIT2(encoding=3,
                                    text='{} (Mp3VoiceStamp)'.format(
                                        self.title))
        tags[self.TAG_ALBUM_TITLE] = TALB(encoding=3, text=self.album_title)
        tags[self.TAG_ALBUM_ARTIST] = TPE2(encoding=3, text=self.album_artist)
        tags[self.TAG_ARTIST] = TPE1(encoding=3, text=self.artist)
        tags[self.TAG_COMPOSER] = TCOM(encoding=3, text=self.composer)
        tags[self.TAG_TRACK_NUMBER] = TRCK(encoding=3, text=self.track_number)

        tags[self.TAG_ORIGINAL_FILENAME] = TOFN(encoding=3,
                                                text=self.file_name)
        tags[self.TAG_SOFTWARE] = TSSE(encoding=3,
                                       text='{app} v{v} {url}'.format(
                                           app=APP_NAME,
                                           v=VERSION,
                                           url=APP_URL))

        tags.save(file_name)
コード例 #4
0
ファイル: md.py プロジェクト: araa47/vidl
def add_metadata(filename, md):
    try:
        tags = ID3(filename)
    except mutagen.id3.ID3NoHeaderError:
        file = mutagen.File(filename)
        file.add_tags()
        tags = file

    if 'title' in md: tags["TIT2"] = TIT2(text=md['title'])
    if 'artist' in md: tags["TPE1"] = TPE1(text=md['artist'])
    if 'album' in md: tags["TALB"] = TALB(text=md['album'])
    if 'album_artist' in md: tags["TPE2"] = TPE2(text=md['album_artist'])
    if 'track_number' in md:
        track_number = str(md['track_number'])
        if 'track_count' in md:
            track_number += '/' + str(md['track_count'])
        tags["TRCK"] = TRCK(encoding=3, text=track_number)
    if 'genre' in md: tags["TCON"] = TCON(text=md['genre'])
    if 'year' in md: tags["TDRC"] = TDRC(text=md['year'])

    if 'comment' in md: tags["COMM"] = COMM(text=md['comment'], lang='eng')
    if 'lyrics' in md: tags["USLT"] = USLT(text=md['lyrics'])
    if 'composer' in md: tags["TCOM"] = TCOM(text=md['composer'])

    for key, value in md.items():
        whitespace = ' ' * (10 - len(key))
        log('  ' + key + ':' + whitespace + pformat(value))

    tags.save(filename)
コード例 #5
0
    def ok_pressed():
        try:
            tags = ID3(_dir + "/" + __dir)
        except:
            print("Adding ID3 header;")
            tags = ID3()

        tags['TRCK'] = TRCK(encoding=3, text=edit_entry_list[TRACK_ID].get())
        tags['TIT2'] = TIT2(encoding=3, text=edit_entry_list[TITLE_ID].get())
        tags['TPE1'] = TPE1(encoding=3, text=edit_entry_list[ARTIST_ID].get())
        tags['TALB'] = TALB(encoding=3, text=edit_entry_list[ALBUM_ID].get())
        tags['TDRC'] = TDRC(encoding=3, text=edit_entry_list[YEAR_ID].get())
        tags['TCOM'] = TCOM(encoding=3,
                            text=edit_entry_list[COMPOSER_ID].get())
        tags['TEXT'] = TEXT(encoding=3,
                            text=edit_entry_list[LYRICIST_ID].get())
        tags['TXXX:PERFORMER'] = TXXX(encoding=3,
                                      desc='PERFORMER',
                                      text=edit_entry_list[PERFORMER_ID].get())

        try:
            tags.save(_dir + "/" + __dir)
        except:
            print("denied")

        new_val = list(tree.item(right_row)['values'])
        for in_id in edit_id:
            if new_val[in_id] != edit_entry_list[in_id].get():
                new_val[in_id] = edit_entry_list[in_id].get()

        tree.item(right_row, values=new_val)

        win.destroy()
コード例 #6
0
    def __update_metadata(self, path = str(), info = dict()):
        with open(path, 'r+b') as mp3f:
            mp3 = MP3(mp3f)
            id3 = ID3()

            track_num = info.get('trackNumber', 1)
            id3.add(TRCK(encoding=3, text=[track_num if track_num > 0 else 1]))

            id3.add(TIT2(encoding=3, text=info['title']))
            id3.add(TPE1(encoding=3, text=[info.get('artist', None)]))
            id3.add(TCOM(encoding=3, text=[info.get('composer', None)]))
            id3.add(TCON(encoding=3, text=[info.get('genre', None)]))
            id3.add(TAL(encoding=3, text=[info.get('album', None)]))

            year = info.get('year', 0)
            if year > 0:
                id3.add(TYER(encoding=3, text=[year]))
            
            if 'albumArtRef' in info and len(info['albumArtRef']) > 0:
                img_url = info['albumArtRef'][0]['url']
                if img_url:
                    req = requests.get(img_url, allow_redirects=True)
                    id3.add(APIC(encoding=3, mime='image/jpeg', type=3, data=req.content))
                    
            mp3.tags = id3
            mp3.save(mp3f)
コード例 #7
0
ファイル: py3tag.py プロジェクト: korseby/py3tag
def mp3_tag(mp3_dirname, mp3_filename, artist, album, track, tracks, title, year, genre, bpms, compilation):
	# Delete existing tags
	try:
		id3 = ID3(mp3_filename)
		id3.delete()
	except ID3NoHeaderError:
		id3 = ID3()
	
	# Artist
	id3.add(TPE1(encoding=3, text=artist))
	
	# Artistsort
	id3.add(TSOP(encoding=3, text=artist))
	
	# Band
	id3.add(TPE2(encoding=3, text=artist))
	
	# Composer
	id3.add(TCOM(encoding=3, text=artist))
	
	# Album
	id3.add(TALB(encoding=3, text=album))
	
	# Albumsort
	id3.add(TSOA(encoding=3, text=album))
	
	# Track
	id3.add(TRCK(encoding=3, text=tracks))
	
	# Title
	id3.add(TIT2(encoding=3, text=title))
	
	# Year
	id3.add(TDRC(encoding=3, text=year))
	
	# Genre
	id3.add(TCON(encoding=3, text=genre))
	
	# BPMs
	id3.add(TBPM(encoding=3, text=bpms))

	# Compilation
	if (compilation):
		id3.add(TCMP(encoding=3, text='1'))
	else:
		id3.add(TCMP(encoding=3, text='0'))
	
	# Cover
	image = str(mp3_dirname + '/Cover.jpg')
	try:
		imagefile = open(image, 'rb').read()
		id3.add(APIC(3, 'image/jpeg', 3, 'Cover', imagefile))
	except:
		print("Warning. No Cover.jpg in directory " + mp3_dirname + ".")
	
	# Save tags to file
	id3.save(mp3_filename, v2_version=4, v1=2)
コード例 #8
0
ファイル: embed-mp3-tags.py プロジェクト: nemec/GPMplaylistDL
def write_metadata(song_f: pathlib.Path):
    metadata_f = song_f.with_suffix('.json')

    if not metadata_f.exists():
        print(f"No metadata for file '{song_f}'. Skipping.")
        return

    with open(metadata_f, 'r') as f:
        metadata = json.load(f)

    mp3 = MP3(str(song_f))
    if mp3.tags is None:
        mp3.add_tags()
    tags = mp3.tags

    title = metadata.get('title')
    if title:
        tags.add(TIT2(encoding=3, text=title))
    artist = metadata.get('artist')
    if artist:
        tags.add(TPE1(encoding=3, text=artist))
    composer = metadata.get('composer')
    if composer:
        tags.add(TCOM(encoding=3, text=composer))
    album = metadata.get('album')
    if artist:
        tags.add(TALB(encoding=3, text=album))
    albumArtist = metadata.get('albumArtist')
    if albumArtist:
        tags.add(TPE2(encoding=3, text=albumArtist))
    genre = metadata.get('genre')
    if genre:
        tags.add(TCON(encoding=3, text=genre))
    tracknum = metadata.get('trackNumber')
    if tracknum:
        tags.add(TRCK(encoding=3, text=str(tracknum)))
    year = metadata.get('year')
    if year:
        tags.add(TDRC(encoding=3, text=str(year)))
    duration = metadata.get('durationMillis')
    if duration:
        tags.add(TLEN(encoding=3, text=str(duration)))

    albumart_f = song_f.with_name('folder.jpg')
    if albumart_f.is_file():
        with open(albumart_f, 'rb') as f:
            tags.add(
                APIC(encoding=3,
                     mime='image/jpeg',
                     type=3,
                     desc='Front Cover',
                     data=f.read()))

    mp3.save()
コード例 #9
0
ファイル: tagHelper.py プロジェクト: memoz/AIGPY
 def _saveMp3(self, coverPath):
     self._handle.tags.add(TIT2(encoding=3, text=self.title))
     self._handle.tags.add(TALB(encoding=3, text=self.album))
     # self._handle.tags.add(TOPE(encoding=3, text=self.albumartist))
     self._handle.tags.add(TPE1(encoding=3, text=self.artist))
     self._handle.tags.add(TCOP(encoding=3, text=self.copyright))
     self._handle.tags.add(TRCK(encoding=3, text=str(self.tracknumber)))
     # self._handle.tags.add(TRCK(encoding=3, text=self.discnum))
     self._handle.tags.add(TCON(encoding=3, text=self.genre))
     self._handle.tags.add(TDRC(encoding=3, text=self.date))
     self._handle.tags.add(TCOM(encoding=3, text=self.composer))
     self._handle.tags.add(TSRC(encoding=3, text=self.isrc))
     self._savePic(coverPath)
     self._handle.save()
     return True
コード例 #10
0
    def write_ID3v2(self):
        if MUTAGEN:
            if "MP3" in self.__audio_codec:
                try:
                    tags = ID3(self.__filepath)
                except ID3NoHeaderError:
                    tags = ID3()

                # Track number
                tags["TRCK"] = TRCK(encoding=3,
                                    text=unicode(self.get_tag("track_number")))
                # Title
                tags["TIT2"] = TIT2(encoding=3,
                                    text=unicode(self.get_tag("title")))
                # Artist
                tags["TPE1"] = TPE1(encoding=3,
                                    text=unicode(self.get_tag("artist")))
                # Album
                tags["TALB"] = TALB(encoding=3,
                                    text=unicode(self.get_tag("album")))
                # Year
                tags["TDRC"] = TDRC(encoding=3,
                                    text=unicode(self.get_tag("year")))
                # Genre
                tags["TCON"] = TCON(encoding=3,
                                    text=unicode(self.get_tag("genre")))
                # Comment
                tags["COMM"] = COMM(encoding=3,
                                    lang=u'eng',
                                    desc='desc',
                                    text=unicode(self.get_tag("comment")))
                #tags["COMM"] = COMM(encoding=3, text=unicode(self.get_tag("comment")))
                # Album artist
                tags["TPE2"] = TPE2(encoding=3,
                                    text=unicode(self.get_tag("album_artist")))
                # Composer
                tags["TCOM"] = TCOM(encoding=3,
                                    text=unicode(self.get_tag("composer")))
                # Disc number
                tags["TPOS"] = TPOS(encoding=3,
                                    text=unicode(self.get_tag("disc_number")))
                # Cover
                tags["APIC"] = APIC(3, 'image/jpeg', 3, 'Front cover',
                                    self.get_tag("cover"))

                #tags.update_to_v24()
                tags.save(self.__filepath, v1=2)
コード例 #11
0
ファイル: tagHelper.py プロジェクト: AIGMix/AIGPY
 def __saveMp3__(self, coverPath):
     if self._handle.tags is None:
         self._handle.add_tags()
     self._handle.tags.add(TIT2(encoding=3, text=self.title))
     self._handle.tags.add(TALB(encoding=3, text=self.album))
     # self._handle.tags.add(TOPE(encoding=3, text=self.albumartist))
     self._handle.tags.add(TPE1(encoding=3, text=self.artist))
     self._handle.tags.add(TCOP(encoding=3, text=self.copyright))
     self._handle.tags.add(TRCK(encoding=3, text=str(self.tracknumber)))
     # self._handle.tags.add(TRCK(encoding=3, text=self.discnum))
     self._handle.tags.add(TCON(encoding=3, text=self.genre))
     self._handle.tags.add(TDRC(encoding=3, text=self.date))
     self._handle.tags.add(TCOM(encoding=3, text=self.composer))
     self._handle.tags.add(TSRC(encoding=3, text=self.isrc))
     self._handle.tags.add(
         USLT(encoding=3, lang=u'eng', desc=u'desc', text=self.lyrics))
     self.__savePic__(coverPath)
     self._handle.save()
     return True
コード例 #12
0
def add_mp3_tag(path_to_mp3):

    # Create MP3File instance.
    if (path_to_mp3 != None):
        folder = "../book/"
        trac = path_to_mp3[path_to_mp3.find(folder) +
                           len(folder):path_to_mp3.find(folder) + len(folder) +
                           3]
        file = path_to_mp3[path_to_mp3.find(folder) +
                           len(folder) + 4:].replace("/", "").replace(
                               "ä", "ae").replace("ö", "oe")
        # create ID3 tag if not present
        try:
            tags = ID3(folder + trac + " " + file)
        except ID3NoHeaderError:
            print "Adding ID3 header;",
            tags = ID3()

        # add all mp3 tags to the mp3 track
        tags["TIT2"] = TIT2(encoding=3, text=unicode(file.replace(".mp3", "")))
        tags["TALB"] = TALB(encoding=3, text=u'The Random Scientist Audiobook')
        tags["TPE2"] = TPE2(encoding=3, text=u'The Random Scientist Audiobook')
        tags["COMM"] = COMM(encoding=3,
                            lang=u'eng',
                            desc='desc',
                            text=u'mutagen comment')
        tags["TPE1"] = TPE1(encoding=3,
                            text=u'Dr. Stefan Dillinger u. Dr. Dominic Helm')
        tags["TCOM"] = TCOM(encoding=3, text=u'mutagen Composer')
        tags["TDRC"] = TDRC(encoding=3, text=u'2017')
        tags["TRCK"] = TRCK(encoding=3, text=unicode(str(int(trac))))

        tags.save(folder + trac + " " + file)

        # add mp3 cover to the mp3 track
        imagedata = open("../TheRandomScientist_small_white.jpg", 'rb').read()

        id3 = ID3(folder + trac + " " + file)
        id3.add(APIC(3, 'image/jpeg', 3, 'Front cover', imagedata))
        #id3.add(TIT2(encoding=3, text=unicode(file.replace(".mp3","")))

        id3.save(v2_version=3)
コード例 #13
0
ファイル: setmetadata.py プロジェクト: zefaxet/tagme
    if x == "-filename":
        pass
    if x == "-title":
        tags["TIT2"] = TIT2(encoding=3, text=arg)
    if x == "-aartist":
        tags["TPE2"] = TPE2(encoding=3, text=arg)
    if x == "-album:":
        tags["TALB"] = TALB(encoding=3, text=arg)  # Album name
    if x == "-tracknum":
        tags["TRCK"] = TRCK(encoding=3, text=arg)
    if x == "-year":
        tags["TDRC"] = TDRC(encoding=3, text=arg)
    if x == "-genre":
        tags["TCON"] = TCON(encoding=3, text=arg)
    if x == "-test": #doesnt work
        tags["TCOM"] = TCOM(encoding=3, text=arg)

tags.save("C:\\Users\\Edward Auttonberry\\Desktop\\Blackened.mp3")

#TALB Album
#TBPM bpm
#TCOM composer
#TCON Content type (Genre) -- Use genres instead of text attribute
#TCOP copyright(c)
#TCMP itunes compilation flag
#TDAT date of recording (ddmm)
#TDEN encoding time
#TEXT lyricist
#TFLT file type
#TIME time of recording (HHMM)
#TIT2 Title
コード例 #14
0
                                                ' - MassTamilan.org',
                                                '').replace(
                                                    '-StarMusiQ.Com',
                                                    '').replace(
                                                        '-MassTamilan.com', '')
                        try:
                            id3.add(TPE2(encoding=3, text=x))
                            id3.add(TSO2(encoding=3, text=x))
                        except:
                            print "***encoding error***"

                    # composer
                    tcom = id3.getall('TCOM')
                    if tcom:
                        try:
                            id3.add(TCOM(encoding=3, text=x))
                            id3.add(TSOC(encoding=3, text=x))
                        except:
                            print "***encoding error***"

                    #ARTIST
                    tpe1 = id3.getall('TPE1')
                    if tpe1:
                        a = str(tpe1[0]).replace(
                            ' - [Masstamilan.In]',
                            '').replace('-[Masstamilan.In]', '').replace(
                                ' [Masstamilan.In]',
                                '').replace(' [Masstamilan.in]', '').replace(
                                    ' - Masstamilan.In', ''
                                ).replace('[Masstamilan.in]', '').replace(
                                    ' - MassTamilan.com', ''
コード例 #15
0
def copyTagsToTranscodedFileMp3(losslessFile, lossyFile):
    #
    # Copy the tags from the losslessFile (.flac) to the lossyFile.
    # All previous tags from the lossyFile will be deleted before the
    # tags from the losslessFile are copied.
    #
    from mutagen.flac import FLAC
    from mutagen.id3 import ID3

    # Read all tags from the flac file
    flacFile = FLAC(losslessFile)
    flacFileTags = flacFile.tags  # Returns a dictionary containing the flac tags

    # Only mp3 files with ID3 headers can be openend.
    # So be sure to add some tags during encoding .wav. to mp3

    # Mapping from Vorbis comments field recommendations to id3v2_4_0
    # For more information about vorbis field recommendations: http://reactor-core.org/ogg-tagging.html
    # For more information about id3v2_4_0 frames: http://www.id3.org/id3v2.4.0-frames
    #
    # Single value tags:
    #  ALBUM              -> TALB
    #  ARTIST             -> TPE1
    #  PUBLISHER          -> TPUB
    #  COPYRIGHT          -> WCOP
    #  DISCNUMBER         -> TPOS
    #  ISRC               -> TSRC
    #  EAN/UPN
    #  LABEL
    #  LABELNO
    #  LICENSE             -> TOWN
    #  OPUS                -> TIT3
    #  SOURCEMEDIA         -> TMED
    #  TITLE               -> TIT2
    #  TRACKNUMBER         -> TRCK
    #  VERSION
    #  ENCODED-BY          -> TENC
    #  ENCODING
    # Multiple value tags:
    #  COMPOSER            -> TCOM
    #  ARRANGER
    #  LYRICIST            -> TEXT
    #  AUTHOR              -> TEXT
    #  CONDUCTOR           -> TPE3
    #  PERFORMER           ->
    #  ENSEMBLE            -> TPE2
    #  PART                -> TIT1
    #  PARTNUMBER          -> TIT1
    #  GENRE               -> TCON
    #  DATE                -> TDRC
    #  LOCATION
    #  COMMENT             -> COMM
    # Other vorbis tags are mapped to TXXX tags

    mp3File = ID3(lossyFile)
    mp3File.delete()

    for key, value in flacFileTags.items():
        if key == 'title':
            # Map to TIT2 frame
            from mutagen.id3 import TIT2
            mp3File.add(TIT2(encoding=3, text=value))
        elif key == 'album':
            # Map to TALB frame
            from mutagen.id3 import TALB
            mp3File.add(TALB(encoding=3, text=value))
        elif key == 'artist':
            # Map to TPE1 frame
            from mutagen.id3 import TPE1
            mp3File.add(TPE1(encoding=3, text=value))
        elif key == 'tracknumber':
            # Map to TRCK frame
            from mutagen.id3 import TRCK
            mp3File.add(TRCK(encoding=3, text=value))
        elif key == 'date':
            # Map to TDRC frame
            from mutagen.id3 import TDRC
            mp3File.add(TDRC(encoding=3, text=value))
        elif key == 'genre':
            # Map to TCON frame
            from mutagen.id3 import TCON
            mp3File.add(TCON(encoding=3, text=value))
        elif key == 'discnumber':
            # Map to TPOS frame
            from mutagen.id3 import TPOS
            mp3File.add(TPOS(encoding=3, text=value))
        elif key == 'composer':
            # Map to TCOM frame
            from mutagen.id3 import TCOM
            mp3File.add(TCOM(encoding=3, text=value))
        elif key == 'conductor':
            # Map to TPE3 frame
            from mutagen.id3 import TPE3
            mp3File.add(TPE3(encoding=3, text=value))
        elif key == 'ensemble':
            # Map to TPE2 frame
            from mutagen.id3 import TPE2
            mp3File.add(TPE2(encoding=3, text=value))
        elif key == 'comment':
            # Map to COMM frame
            from mutagen.id3 import COMM
            mp3File.add(COMM(encoding=3, text=value))
        elif key == 'publisher':
            # Map to TPUB frame
            from mutagen.id3 import TPUB
            mp3File.add(TPUB(encoding=3, text=value))
        elif key == 'opus':
            # Map to TIT3 frame
            from mutagen.id3 import TIT3
            mp3File.add(TIT3(encoding=3, text=value))
        elif key == 'sourcemedia':
            # Map to TMED frame
            from mutagen.id3 import TMED
            mp3File.add(TMED(encoding=3, text=value))
        elif key == 'isrc':
            # Map to TSRC frame
            from mutagen.id3 import TSRC
            mp3File.add(TSRC(encoding=3, text=value))
        elif key == 'license':
            # Map to TOWN frame
            from mutagen.id3 import TOWN
            mp3File.add(TOWN(encoding=3, text=value))
        elif key == 'copyright':
            # Map to WCOP frame
            from mutagen.id3 import WCOP
            mp3File.add(WCOP(encoding=3, text=value))
        elif key == 'encoded-by':
            # Map to TENC frame
            from mutagen.id3 import TENC
            mp3File.add(TENC(encoding=3, text=value))
        elif (key == 'part' or key == 'partnumber'):
            # Map to TIT3 frame
            from mutagen.id3 import TIT3
            mp3File.add(TIT3(encoding=3, text=value))
        elif (key == 'lyricist' or key == 'textwriter'):
            # Map to TEXT frame
            from mutagen.id3 import TIT3
            mp3File.add(TIT3(encoding=3, text=value))
        else:  #all other tags are mapped to TXXX frames
            # Map to TXXX frame
            from mutagen.id3 import TXXX
            mp3File.add(TXXX(encoding=3, text=value, desc=key))

        mp3File.update_to_v24()
        mp3File.save()

    return
コード例 #16
0
ファイル: base.py プロジェクト: apocalyptech/exordium
    def update_mp3(self,
                   filename,
                   artist=None,
                   album=None,
                   title=None,
                   tracknum=None,
                   maxtracks=None,
                   year=None,
                   group=None,
                   conductor=None,
                   composer=None):
        """
        Updates an on-disk mp3 with the given tag data.  Any passed-in
        variable set to None will be ignored.  It's possible there could
        be some problems with ID3v2.3 vs. ID3v2.4 tags in here - I don't
        know if mutagen does an auto-convert.  I think it might.

        If group/conductor/composer is a blank string, those fields will
        be completely removed from the file.  Any of the other fields set
        to blank will leave the tag in place.

        Will ensure that the file's mtime is updated.
        """

        full_filename = self.check_library_filename(filename)
        self.assertEqual(os.path.exists(full_filename), True)

        starting_mtime = int(os.stat(full_filename).st_mtime)

        tags = ID3(full_filename)

        if artist is not None:
            tags.delall('TPE1')
            tags.add(TPE1(encoding=3, text=artist))

        if album is not None:
            tags.delall('TALB')
            tags.add(TALB(encoding=3, text=album))

        if title is not None:
            tags.delall('TIT2')
            tags.add(TIT2(encoding=3, text=title))

        if group is not None:
            tags.delall('TPE2')
            if group != '':
                tags.add(TPE2(encoding=3, text=group))

        if conductor is not None:
            tags.delall('TPE3')
            if conductor != '':
                tags.add(TPE3(encoding=3, text=conductor))

        if composer is not None:
            tags.delall('TCOM')
            if composer != '':
                tags.add(TCOM(encoding=3, text=composer))

        if tracknum is not None:
            tags.delall('TRCK')
            if maxtracks is None:
                tags.add(TRCK(encoding=3, text=str(tracknum)))
            else:
                tags.add(TRCK(encoding=3,
                              text='%s/%s' % (tracknum, maxtracks)))

        if year is not None:
            tags.delall('TDRC')
            tags.delall('TDRL')
            tags.delall('TYER')
            tags.add(TDRC(encoding=3, text=str(year)))

        # Save
        tags.save()

        # Check on mtime update and manually fix it if it's not updated
        self.bump_mtime(starting_mtime, full_filename=full_filename)
コード例 #17
0
ファイル: base.py プロジェクト: apocalyptech/exordium
    def add_mp3(self,
                path='',
                filename='file.mp3',
                artist='',
                album='',
                title='',
                tracknum=0,
                maxtracks=None,
                year=0,
                yeartag='TDRC',
                group='',
                conductor='',
                composer='',
                basefile='silence-vbr.mp3',
                save_as_v23=False,
                apply_tags=True):
        """
        Adds a new mp3 with the given parameters to our library.

        Pass in ``save_as_v23`` as ``True`` to have the file save with an ID3v2.3
        tag, instead of ID3v2.4.  One of the main tag-level changes which
        will happen there is conversion of the year tag to TYER, which
        we'll otherwise not be specifying directly.  ``yeartag`` is effectively
        ignored when ``save_as_v23`` is True.

        Pass in ``False`` for ``apply_tags`` to only use whatever tags happen to
        be present in the source basefile.

        Returns the full filename of the added file.
        """

        full_filename = self.add_file(basefile, filename, path=path)

        # Finish here if we've been told to.
        if not apply_tags:
            return full_filename

        # Apply the tags as specified
        tags = ID3()
        tags.add(TPE1(encoding=3, text=artist))
        tags.add(TALB(encoding=3, text=album))
        tags.add(TIT2(encoding=3, text=title))

        if group != '':
            tags.add(TPE2(encoding=3, text=group))
        if conductor != '':
            tags.add(TPE3(encoding=3, text=conductor))
        if composer != '':
            tags.add(TCOM(encoding=3, text=composer))

        if maxtracks is None:
            tags.add(TRCK(encoding=3, text=str(tracknum)))
        else:
            tags.add(TRCK(encoding=3, text='%s/%s' % (tracknum, maxtracks)))

        if yeartag == 'TDRL':
            tags.add(TDRL(encoding=3, text=str(year)))
        elif yeartag == 'TDRC':
            tags.add(TDRC(encoding=3, text=str(year)))
        else:
            raise Exception('Unknown year tag specified: %s' % (yeartag))

        # Convert to ID3v2.3 if requested.
        if save_as_v23:
            tags.update_to_v23()

        # Save to our filename
        tags.save(full_filename)

        # Return
        return full_filename
コード例 #18
0
ファイル: recipe-577138.py プロジェクト: zlrs/code-1
                                     lang=u'eng',
                                     desc=u'desc',
                                     text=lyrics))
        print 'Added USLT frame to', fn

        # set title from filename; adjust to your needs
        if SET_OTHER_ID3_TAGS:
            title = unicode(os.path.splitext(os.path.split(fn)[-1])[0])
            print title,
            print fname
            # title
            tags["TIT2"] = TIT2(encoding=3, text=title)
            tags["TALB"] = TALB(encoding=3, text=u'mutagen Album Name')
            tags["TPE2"] = TPE2(encoding=3, text=u'mutagen Band')
            tags["COMM"] = COMM(encoding=3,
                                lang=u'eng',
                                desc='desc',
                                text=u'mutagen comment')
            # artist
            tags["TPE1"] = TPE1(encoding=3, text=u'mutagen Artist')
            # composer
            tags["TCOM"] = TCOM(encoding=3, text=u'mutagen Composer')
            # genre
            tags["TCON"] = TCON(encoding=3, text=u'mutagen Genre')
            tags["TDRC"] = TDRC(encoding=3, text=u'2010')
            #use to set track number
            #tags["TRCK"] = COMM(encoding=3, text=track_number)
        tags.save(fname)

print 'Done'
コード例 #19
0
ファイル: metadata.py プロジェクト: lhansford/beatbox
    def save_mp3_metadata(self, file_path, data):
        """ Saves the given metadata for an MP3 file.

		Metadata.save_mp3_metadata(str, dict)
		"""
        audio = ID3(file_path)  # Writing MP3 tags needs ID3
        mp3_audio, format = self.get_mutagen_parser(file_path)

        if data.get("title"):
            audio.add(TIT2(encoding=3, text=unicode(data['title'])))
        if data.get("artist"):
            audio.add(TPE1(encoding=3, text=unicode(data['artist'])))
        if data.get("album"):
            audio.add(TALB(encoding=3, text=unicode(data['album'])))
        if data.get("genre"):
            audio.add(TCON(encoding=3, text=unicode(data['genre'])))
        if data.get("year"):
            audio.add(TDRC(encoding=3, text=unicode(data['year'])))
        if data.get("album_artist"):
            audio.add(TPE2(encoding=3, text=unicode(data['album_artist'])))

        if data.get("track_number", False) and data.get("total_tracks", False):
            audio.add(
                TRCK(encoding=3,
                     text=unicode(data['track_number'] + '/' +
                                  data['total_tracks'])))
        elif data.get("track_number"):
            total_tracks = self.get_total_tracks(mp3_audio, format)
            if total_tracks == None:
                audio.add(TRCK(encoding=3, text=unicode(data['track_number'])))
            else:
                audio.add(
                    TRCK(encoding=3,
                         text=unicode(data['track_number'] + '/' +
                                      total_tracks)))
        elif data.get("total_tracks"):
            t_no = self.get_track_number(mp3_audio, format)
            if t_no == None:
                audio.add(
                    TRCK(encoding=3,
                         text=unicode(" /" + data["total_tracks"])))
            else:
                audio.add(
                    TRCK(encoding=3,
                         text=unicode(t_no + '/' + data["total_tracks"])))

        if data.get("disc_number", False) and data.get("total_discs", False):
            audio.add(
                TPOS(encoding=3,
                     text=unicode(data['disc_number'] + '/' +
                                  data['total_discs'])))
        elif data.get("disc_number"):
            total_discs = self.get_total_discs(mp3_audio, format)
            if total_discs == None:
                audio.add(TPOS(encoding=3, text=unicode(data['disc_number'])))
            else:
                audio.add(
                    TPOS(encoding=3,
                         text=unicode(data['disc_number'] + '/' +
                                      total_discs)))
        elif data.get("total_discs"):
            d_no = self.get_disc_number(mp3_audio, format)
            if d_no == None:
                audio.add(
                    TPOS(encoding=3, text=unicode(" /" + data["total_discs"])))
            else:
                audio.add(
                    TPOS(encoding=3,
                         text=unicode(d_no + '/' + data["total_discs"])))

        if data.get("composer"):
            audio.add(TCOM(encoding=3, text=unicode(data['composer'])))
        if data.get("publisher"):
            audio.add(TPUB(encoding=3, text=unicode(data['publisher'])))
        if data.get("comments"):
            audio.add(
                COMM(encoding=3,
                     lang="eng",
                     desc="",
                     text=unicode(data['comments'])))
        audio.save()
コード例 #20
0
ファイル: YuPyMu.py プロジェクト: UntraceableBarosaur/YuPyMu
def formatSong(ydlDataStorage):
    imagefname = str(prgmPath + "/" + albumName + "/" + 'Track_' +
                     str(trackcount) + ".jpg")
    print("Thumbnail path for Track # " + str(trackcount) + " : ")
    print(imagefname)
    fname = str(prgmPath + "/" + albumName + "/" + 'Track_' + str(trackcount) +
                ".mp3")
    fname = fname.replace(":", " -")
    fname = fname.replace('None', "NA")
    fname = fname.replace("|", "_")
    print("File path for Track # " + str(trackcount) + " : ")
    print(fname)
    #trackCategories = "36"
    """~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
    response = requests.get(
        str('https://i.ytimg.com/vi/' +
            str(ydlDataStorage['entries'][0]['id']) + '/maxresdefault.jpg'),
        stream=True)
    with open(imagefname, 'wb') as out_file:
        shutil.copyfileobj(response.raw, out_file)
    del response
    """~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
    THUMB_SIZE = 360, 360
    img = PIL.Image.open(imagefname)
    width, height = img.size

    if width > height:
        delta = width - height
        left = int(delta / 2)
        upper = 0
        right = height + left
        lower = height
    else:
        delta = height - width
        left = 0
        upper = int(delta / 2)
        right = width
        lower = width + upper

    img = img.crop((left, upper, right, lower))
    img.thumbnail(THUMB_SIZE, PIL.Image.ANTIALIAS)
    img.save(imagefname)
    """~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
    # create ID3 tag if not present
    try:
        tags = ID3(fname)
    except ID3NoHeaderError:
        print "Adding ID3 header;",
        tags = ID3()

    tags["APIC"] = APIC(encoding=3,
                        mime='image/jpeg',
                        desc=u'%s' % (imagefname),
                        data=open(imagefname).read())
    tags["TIT2"] = TIT2(
        encoding=3,
        text=u'%s' %
        (getListedVariable(trackTitleInputVars, "Unknown Title").replace(
            replaceString, "")[int(replaceFirst):]))
    tags["TALB"] = TALB(
        encoding=3,
        text=u'%s' % (getListedVariable(trackAlbumInputVars, "Unknown Album")))
    tags["TPE1"] = TPE1(
        encoding=3,
        text=u'%s' %
        (getListedVariable(trackArtistInputVars, "Unknown Artist")))
    tags["TCOM"] = TCOM(
        encoding=3,
        text=u'%s' %
        (getListedVariable(trackComposerInputVars, "Unknown Composer")))
    tags["TDRC"] = TDRC(encoding=3,
                        text=u'%s' %
                        (getListedVariable(trackYearInputVars, "2000")))
    tags["TRCK"] = TRCK(encoding=3,
                        text=u'%s' %
                        (str(trackcount) + "/" + str(totaltracks)))
    #tags["COMM"] = COMM(encoding=3, lang=u'eng', desc='desc', text=u'mutagen comment')
    #tags["TCON"] = TCON(encoding=3, text=u'%s'%(trackCategories))

    tags.save(fname)
コード例 #21
0
ファイル: transcoder.py プロジェクト: markbaaijens/transcoder
def CopyTagsToTranscodedFileMp3(losslessFile, lossyFile):  
    # Because the input flac file is decoded to wav, all metadata is lost. We have to extract this metadata from 
    # the flac file and put it directly into the generated mp3 file.
    from mutagen.flac import FLAC
    from mutagen.id3 import ID3   
    
    flacFile = FLAC(losslessFile)
    flacFileTags = flacFile.tags 
          
    mp3File = ID3(lossyFile)    
    mp3File.delete()    
        
    for key,value in flacFileTags.items():
        if key == 'title': 
            from mutagen.id3 import TIT2
            mp3File.add(TIT2(encoding=3, text=value)) 
        elif key == 'album': 
            from mutagen.id3 import TALB
            mp3File.add(TALB(encoding=3, text=value))
        elif key == 'artist': 
            from mutagen.id3 import TPE1
            mp3File.add(TPE1(encoding=3, text=value)) 
        elif key == 'tracknumber': 
            from mutagen.id3 import TRCK
            mp3File.add(TRCK(encoding=3, text=value))
        elif key == 'date': 
            from mutagen.id3 import TDRC
            mp3File.add(TDRC(encoding=3, text=value))
        elif key == 'genre': 
            from mutagen.id3 import TCON
            mp3File.add(TCON(encoding=3, text=value))
        elif key == 'discnumber': 
            from mutagen.id3 import TPOS
            mp3File.add(TPOS(encoding=3, text=value))
        elif key == 'composer': 
            from mutagen.id3 import TCOM
            mp3File.add(TCOM(encoding=3, text=value))
        elif key == 'conductor': 
            from mutagen.id3 import TPE3
            mp3File.add(TPE3(encoding=3, text=value))
        elif key == 'ensemble': 
            from mutagen.id3 import TPE2
            mp3File.add(TPE2(encoding=3, text=value))      
        elif key == 'comment': 
            from mutagen.id3 import COMM
            mp3File.add(COMM(encoding=3, text=value))
        elif key == 'publisher': 
            from mutagen.id3 import TPUB
            mp3File.add(TPUB(encoding=3, text=value))
        elif key == 'opus': 
            from mutagen.id3 import TIT3
            mp3File.add(TIT3(encoding=3, text=value))
        elif key == 'sourcemedia': 
            from mutagen.id3 import TMED
            mp3File.add(TMED(encoding=3, text=value))
        elif key == 'isrc': 
            from mutagen.id3 import TSRC
            mp3File.add(TSRC(encoding=3, text=value))
        elif key == 'license': 
            from mutagen.id3 import TOWN
            mp3File.add(TOWN(encoding=3, text=value))
        elif key == 'copyright': 
            from mutagen.id3 import WCOP
            mp3File.add(WCOP(encoding=3, text=value))
        elif key == 'encoded-by': 
            from mutagen.id3 import TENC
            mp3File.add(TENC(encoding=3, text=value))
        elif (key == 'part' or key == 'partnumber'): 
            from mutagen.id3 import TIT3
            mp3File.add(TIT3(encoding=3, text=value))
        elif (key == 'lyricist' or key == 'textwriter'): 
            from mutagen.id3 import TIT3
            mp3File.add(TIT3(encoding=3, text=value))
        else: 
            from mutagen.id3 import TXXX
            mp3File.add(TXXX(encoding=3, text=value, desc=key))        
      
        mp3File.update_to_v24()
        mp3File.save() 
      
    return
コード例 #22
0
 def composer(self, composer: str):
     self.file['TCOM'] = TCOM(encoding=3, text=composer)
     return self
    return (int(numberPart), letterPart)


advanced.sort(key=weirdSort)
intermediate.sort(key=weirdSort)
essential.sort(key=weirdSort)

for i, file in enumerate(advanced):
    print(file)
    audioFile = ID3(filesDir + file)
    # print(audioFile)
    # print(audioFile.keys())
    # print(audioFile['TCOM'])
    audioFile.add(TALB(encoding=0, text=[u"French - Advanced"]))
    audioFile.add(TIT2(encoding=0, text=[file[3:-4]]))
    audioFile.add(TCOM(encoding=0, text=[u"Living Language"]))
    audioFile.add(TPE1(encoding=0, text=[u"Living Language"]))
    audioFile.add(TPE2(encoding=0, text=[u"Living Language"]))
    audioFile.add(TRCK(encoding=0, text=[str(i + 1)]))
    audioFile.save()

for i, file in enumerate(intermediate):
    print(file)
    audioFile = ID3(filesDir + file)
    # print(audioFile)
    # print(audioFile.keys())
    # print(audioFile['TCOM'])
    audioFile.add(TALB(encoding=0, text=[u"French - Intermediate"]))
    audioFile.add(TIT2(encoding=0, text=[file[3:-4]]))
    audioFile.add(TCOM(encoding=0, text=[u"Living Language"]))
    audioFile.add(TPE1(encoding=0, text=[u"Living Language"]))