当前位置: 首页>>代码示例>>Python>>正文


Python File.save方法代码示例

本文整理汇总了Python中mutagen.File.save方法的典型用法代码示例。如果您正苦于以下问题:Python File.save方法的具体用法?Python File.save怎么用?Python File.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在mutagen.File的用法示例。


在下文中一共展示了File.save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: postProcessSong

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import save [as 别名]
 def postProcessSong(self, song):
   if self.shouldGenerateTags:
     try:
       name = self.getSongPath(song)
       localList = song.name.split("- ") #The song should be split as "artist - title". If not, it won't be recognized
       artist = localList[0] if len(localList) > 1 else self.defaultArtist #The artist is usually first if its there. Otherwise no artist
       if self.allSongsDefaultArtist: artist = self.defaultArtist
       title = localList[1] if len(localList) > 1 else localList[0] #If there is no artist, the whole name is the title
       
       artist = artist.lstrip().rstrip()
       title  =  title.lstrip().rstrip()
       
       #Appreciate this. It took upwards of 5 hours to get the damn software to do this.
       try:
         songID = EasyID3(name)
       except ID3NoHeaderError:
         songID = MutagenFile(name, easy = True)
         songID.add_tags()
       songID['artist'] = artist
       songID['title'] = title
       songID.save()
       songID = ID3(name, v2_version=3) #EasyID3 doesn't support saving as 2.3 to get Windows to recognize it
       songID.update_to_v23()
       songID.save(v2_version=3)
     except FileNotFoundError:
       debug("File not found for: ", name)
开发者ID:civilwargeeky,项目名称:MusicDownloader,代码行数:28,代码来源:MusicUpdater.py

示例2: tag

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import save [as 别名]
    def tag(self):
        data = self.get_parent_instance().metadata()

        with tempfile.NamedTemporaryFile(suffix='-musicdb.mp3') as f:
            # Download
            with default_storage.open(self.file.location) as g:
                contents = g.read()

            f.write(contents)
            f.flush()
            f.seek(0)

            audio = MutagenFile(f.name)
            audio.delete()

            if isinstance(audio, mp3.MP3):
                audio.tags = easyid3.EasyID3()

            audio.update(data)
            audio.save()

            self.length = int(audio.info.length)

            # Copy it back
            default_storage.delete(self.file.location)
            dst = default_storage.save(self.file.location, DjangoFile(f))

            assert dst == self.file.location
开发者ID:lamby,项目名称:musicdb,代码行数:30,代码来源:models.py

示例3: tag

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import save [as 别名]
def tag(filename, data):
    audio = File(filename)
    audio.delete()
    if isinstance(audio, mp3.MP3):
        audio.tags = easyid3.EasyID3()
    audio.update(data)
    audio.save()
开发者ID:MechanisM,项目名称:musicdb,代码行数:9,代码来源:tagging.py

示例4: TFileType

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import save [as 别名]
class TFileType(TestCase):

    def setUp(self):
        self.vorbis = File(os.path.join(DATA_DIR, "empty.ogg"))

        filename = get_temp_copy(os.path.join(DATA_DIR, "xing.mp3"))
        self.mp3_notags = File(filename)
        self.mp3_filename = filename

    def tearDown(self):
        os.remove(self.mp3_filename)

    def test_delitem_not_there(self):
        self.failUnlessRaises(KeyError, self.vorbis.__delitem__, "foobar")

    def test_add_tags(self):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            self.failUnlessRaises(NotImplementedError, FileType().add_tags)

    def test_delitem(self):
        self.vorbis["foobar"] = "quux"
        del(self.vorbis["foobar"])
        self.failIf("quux" in self.vorbis)

    def test_save_no_tags(self):
        self.assertTrue(self.mp3_notags.tags is None)
        self.assertTrue(self.mp3_notags.filename)
        self.mp3_notags.save()
        self.assertTrue(self.mp3_notags.tags is None)
开发者ID:gdelfresno,项目名称:mutagen,代码行数:32,代码来源:test___init__.py

示例5: write_info2file

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import save [as 别名]
    def write_info2file(self, info):
        # open file with mutagen
        audio = File(info['filename'], easy=True)
        if audio is None:
            return

        # write title+album information into audio files
        if audio.tags is None:
            audio.add_tags()

        # write album+title
        if info['album'] is not None:
            audio.tags['album'] = info['album']
        if info['title'] is not None:
            audio.tags['title'] = info['title']

        # write genre tag
        if self.container.config.genre_tag is not None:
            audio.tags['genre'] = self.container.config.genre_tag
        else:
            audio.tags['genre'] = ''

        # write pubDate
        if info['pubDate'] is not None:
            audio.tags['date'] = info['pubDate']

        audio.save()
开发者ID:fk-lx,项目名称:gpodder,代码行数:29,代码来源:tagging.py

示例6: TFileType

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import save [as 别名]
class TFileType(TestCase):

    def setUp(self):
        self.vorbis = File(os.path.join(DATA_DIR, "empty.ogg"))

        fd, filename = mkstemp(".mp3")
        os.close(fd)
        shutil.copy(os.path.join(DATA_DIR, "xing.mp3"), filename)
        self.mp3_notags = File(filename)
        self.mp3_filename = filename

    def tearDown(self):
        os.remove(self.mp3_filename)

    def test_delitem_not_there(self):
        self.failUnlessRaises(KeyError, self.vorbis.__delitem__, "foobar")

    def test_add_tags(self):
        self.failUnlessRaises(NotImplementedError, FileType().add_tags)

    def test_delitem(self):
        self.vorbis["foobar"] = "quux"
        del(self.vorbis["foobar"])
        self.failIf("quux" in self.vorbis)

    def test_save_no_tags(self):
        self.assertTrue(self.mp3_notags.tags is None)
        self.mp3_notags.save()
        self.assertTrue(self.mp3_notags.tags is None)
开发者ID:akerbis,项目名称:mutagen,代码行数:31,代码来源:test___init__.py

示例7: ensure_id3_tag_present

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import save [as 别名]
def ensure_id3_tag_present(filepath):
    try:
        meta = EasyID3(filepath)
    except ID3NoHeaderError:
        meta = File(filepath, easy=True)
        meta.add_tags()
        meta.save()
开发者ID:daveystruijk,项目名称:music-library,代码行数:9,代码来源:analyze.py

示例8: write_basic_tags

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import save [as 别名]
    def write_basic_tags(self, modify_tags, set_artist_to_album, set_version):
        audio = File(self.filename, easy=True)

        if audio.tags is None:
            audio.add_tags()

        if modify_tags:
            if self.album is not None:
                audio.tags['album'] = self.album

            if self.title is not None:
                audio.tags['title'] = self.title

            if self.genre is not None:
                audio.tags['genre'] = self.genre

            if self.pubDate is not None:
                audio.tags['date'] = self.pubDate

            if set_artist_to_album:
                audio.tags['artist'] = self.album

        if type(audio) is EasyMP3:
            audio.save(v2_version=set_version)
        else:
            # Not actually audio
            audio.save()
开发者ID:gpodder,项目名称:gpodder,代码行数:29,代码来源:tagging.py

示例9: fixup_ID3

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import save [as 别名]
def fixup_ID3(fname: Union[str, MusicFileType]) -> None:
    '''Convert RVA2 tags to TXXX:replaygain_* tags.

    Argument should be an MusicFile (instance of mutagen.FileType) or
    a string, which will be loaded by mutagen.MusicFile. If it is an
    instance of mutagen.id3.ID3FileType, the ReplayGain information in
    the RVA2 tags (if any) will be propagated to 'TXXX:replaygain_*'
    tags. Thus the resulting file will have the ReplayGain information
    encoded both ways for maximum compatibility.

    If the track is an instance of 'mutagen.mp3.EasyMP3', it will be
    re-opened as the non-easy equivalent, since EasyMP3 maps the
    replaygain tags to RVA2, preventing the editing of the TXXX tags.

    This function modifies the file on disk.

    '''
    # Make sure we have the non-easy variant.
    if isinstance(fname, MusicFileType):
        fname = fname.filename
    track = MusicFile(fname, easy=False)
    # Only operate on ID3
    if not isinstance(track, id3.ID3FileType):
        return

    # Get the RVA2 frames
    try:
        track_rva2 = track['RVA2:track']
        if track_rva2.channel != 1:
            track_rva2 = None
    except KeyError:
        track_rva2 = None
    try:
        album_rva2 = track['RVA2:album']
        if album_rva2.channel != 1:
            album_rva2 = None
    except KeyError:
        album_rva2 = None

    # Add the other tags based on RVA2 values
    if track_rva2:
        track['TXXX:replaygain_track_peak'] = \
            id3.TXXX(encoding=id3.Encoding.UTF8,
                     desc='replaygain_track_peak',
                     text=format_peak(track_rva2.peak))
        track['TXXX:replaygain_track_gain'] = \
            id3.TXXX(encoding=id3.Encoding.UTF8,
                     desc='replaygain_track_gain',
                     text=format_gain(track_rva2.gain))
    if album_rva2:
        track['TXXX:replaygain_album_peak'] = \
            id3.TXXX(encoding=id3.Encoding.UTF8,
                     desc='replaygain_album_peak',
                     text=format_peak(album_rva2.peak))
        track['TXXX:replaygain_album_gain'] = \
            id3.TXXX(encoding=id3.Encoding.UTF8,
                     desc='replaygain_album_gain',
                     text=format_gain(album_rva2.gain))
    track.save()
开发者ID:DarwinAwardWinner,项目名称:rganalysis,代码行数:61,代码来源:fixup_id3.py

示例10: set_tags

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import save [as 别名]
 def set_tags(cls, audiobook, file_name):
     tags = getattr(audiobook, "%s_tags" % cls.ext)['tags']
     if not tags.get('flac_sha1'):
         tags['flac_sha1'] = audiobook.get_source_sha1()
     audio = File(file_name)
     for k, v in tags.items():
         audio[k] = v
     audio.save()
开发者ID:fnp,项目名称:audio,代码行数:10,代码来源:tasks.py

示例11: Tag

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import save [as 别名]
class Tag(object):
    def __init__(self, filename):
        self.tags = File(filename, easy=True)
        if self.tags == None:
            raise TagTypeError()

    @property
    def album(self):
        return self.tags.get('album')

    @album.setter
    def album(self, value):
        self.tags['album'] = value

    @album.deleter
    def album(self):
        del self.tags['album']

    @property
    def artist(self):
        return self.tags.get('artist')

    @artist.setter
    def artist(self, value):
        self.tags['artist'] = value

    @artist.deleter
    def artist(self):
        del self.tags['artist']


    @property
    def title(self):
        return self.tags.get('title')

    @title.setter
    def title(self, value):
        self.tags['title'] = value

    @title.deleter
    def title(self):
        del self.tags['title']


    @property
    def track(self):
        return self.tags.get('tracknumber')

    @track.setter
    def track(self, value):
        self.tags['tracknumber'] = value

    @track.deleter
    def track(self):
        del self.tags['tracknumber']

    def save(self):
        self.tags.save();
开发者ID:terrasea,项目名称:music-file-tag-tree-sorter,代码行数:60,代码来源:tag.py

示例12: set_track_metadata

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import save [as 别名]
    def set_track_metadata(self, track = None, filename = None, url = None):
        """Find and set all metadata for a track"""
        if url == None or track == None:
            return None

        if filename == None:
            filename = get_track_filename(url)

        # id3 is only for mp3
        if not filename.endswith(".mp3"):
            if filename.endswith(".wav"):
                filename = self.convert_wav_to_mp3(filename)
            else:
                return None


        # Set title
        try:
            meta = ID3(filename)
        except ID3NoHeaderError:
            try:
                meta = File(filename, easy=True)
                meta.add_tags()
                meta.save()
                meta = ID3(filename)
            except:
                return
        except IOError:
            return

        try:
            meta.add(TIT2(encoding=3, text=track.title))
            meta.add(TCON(encoding=3, text=track.genre))
            meta.add(TCOM(encoding=3, text=track.user["username"]))
            meta.save()

            artwork_filename = wget.download(track.artwork_url)

            audio = MP3(filename, ID3=ID3)

            # add ID3 tag if it doesn't exist
            try:
                audio.add_tags()
            except error:
                pass

            audio.tags.add(
                APIC(
                    encoding=3, # 3 is for utf-8
                    mime='image/jpeg', # image/jpeg or image/png
                    type=3, # 3 is for the cover image
                    desc=u'Cover',
                    data=open(artwork_filename).read()
                )
            )
            audio.save()
        except:
            return 
开发者ID:donnell74,项目名称:SoundDown,代码行数:60,代码来源:main.py

示例13: update_album_cover

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import save [as 别名]
def update_album_cover(filename, new_cover):
    conf = get_or_create_config()
    bak_conf = conf.copy()
    song_album = ''
    for album in bak_conf['library']:
        for i, song in enumerate(bak_conf['library'][album]['songs']):
            if song == filename:
                song_album = album

                image = Image.open(new_cover)
                output = StringIO.StringIO()
                image.save(output, format="JPEG")
                data = output.getvalue()
                output.close()

                audio = File(filename)
                audio.tags.add(
                    APIC(
                        encoding=3, # 3 is for utf-8
                        mime='image/jpeg', # image/jpeg or image/png
                        type=3, # 3 is for the cover image
                        desc=u'',
                        data=data
                    )
                )
                #from PyQt4.QtCore import pyqtRemoveInputHook
                #pyqtRemoveInputHook()
                #from IPython.Shell import IPShellEmbed; IPShellEmbed()()
                audio.save()
                break
        if song_album:
            break
    covers = set()
    for i, song in enumerate(bak_conf['library'][song_album]['songs']):
        covers.add(get_full_song_info(song)[4])
    if len(covers) == 1:
        data = covers.pop()
        #print data
        if data: #all new cover are the same, updating album cover
            song_file = File(filename)
            album_name = get_cover_hash(song_file)
            iconpath = os.path.join(ROOT_PATH,'cover_cache',album_name+'.png')
            iconpath_jpg = os.path.join(ROOT_PATH,'cover_cache',album_name+'.jpg')
            with open(iconpath_jpg, 'wb') as img:
                img.write(data)
            im = Image.open(iconpath_jpg)
            #im = im.resize((cover_size, cover_size), Image.ANTIALIAS)
            im.thumbnail((cover_size,cover_size), Image.ANTIALIAS)
            im.save(iconpath)
            try:
                os.remove(iconpath_jpg)
            except:
                pass
            conf['library'][song_album]['cover'] = getCoverArt(filename)[0]

    save_config(conf)
开发者ID:fabiomdiniz,项目名称:Frey,代码行数:58,代码来源:tanooki_library.py

示例14: metadata

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import save [as 别名]
    def metadata(self):
        """ Updates metadata
        """
        print("Starting to update metadata") 
        glib = self.glib
        db = self.db
        man = self.man
        mMeta = {}
        for g in man.getAllMeta():
            mMeta[g[0]] = {'title':g[1], 'artist':g[3], 'albumArtist':g[4], 'album':g[2], 'genre':g[6], 'trackNumber':g[7], 'totalTrackCount':g[8], 'diskNumber':g[9], 'totalDiskCount':g[10]}
        for i in glib:
            lid = db.getGLID(i['id'])
            if not lid:
                continue 
            ipath = db.getPath(lid)
            try:
                m = mMeta[i['id']]
            except KeyError:
                db.addGID(lid, None)
                continue 
            tags = [t for t in m for j in i if t == j]
            nMatch = []
            for t in tags:
                if m[t] != i[t]:
                    nMatch += [t]
            if nMatch:
                if '.mp3' in ipath or '.m4a' in ipath:
                    try:
                        sng = GLB(ipath, easy=True) 
                    except IOError:
                        db.remove(lid)
                        continue
                else:
                    continue
                for n in nMatch:
                    if '.mp3' in ipath and n == 'albumArtist':
                        sng['performer'] = [i['albumArtist']]
                        man.setMeta(i['id'], 'MusicAlbumArtist', i['albumArtist'])
                    else:
                        if n in ('trackNumber', 'totalTrackCount', 'diskNumber', 'totalDiskCount'):
                            if n in ('trackNumber', 'totalTrackCount'):
                                sng['tracknumber'] = [str(i['trackNumber']) + '/' + str(i['totalTrackCount'])]
                                man.setMeta(i['id'], 'MusicTrackNumber', int(i['trackNumber']))
                                man.setMeta(i['id'], 'MusicTrackCount', int(i['totalTrackCount']))
                            else:
                                sng['disknumber'] = [str(i['diskNumber']) + '/' + str(i['totalDiskCount'])]
                                man.setMeta(i['id'], 'MusicDiscNumber', int(i['discNumber']))
                                man.setMeta(i['id'], 'MusicDiscCount', int(i['totalDiscCount']))
                        else:
                            sng[n.lower()] = [i[n]]
                            man.setMeta(i['id'], n.lower().replace('title', 'MusicName').replace('albumArtist', 'MusicAlbumArtist').replace('album', 'MusicAlbum').replace('artist', 'MusicArtist').replace('genre', 'MusicGenre'), i[n])
                    db.setUpMeta(lid)
                sng.save()


        print("Finished updating metadata")
开发者ID:nourhkhattab,项目名称:Synch-Local,代码行数:58,代码来源:synch.py

示例15: insert_coverart

# 需要导入模块: from mutagen import File [as 别名]
# 或者: from mutagen.File import save [as 别名]
    def insert_coverart(self):
        audio = File(self.filename)

        if self.cover.endswith('png'):
            cover_format = MP4Cover.FORMAT_PNG
        else:
            cover_format = MP4Cover.FORMAT_JPEG

        data = open(self.cover, 'rb').read()
        audio.tags['covr'] =  [MP4Cover(data, cover_format)]
        audio.save()
开发者ID:skysign,项目名称:gpodder,代码行数:13,代码来源:tagging.py


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