Ejemplo n.º 1
0
def migrate_mediafile_to_episode(config, filename, show):
    from datetime import datetime, date, timedelta
    from capturadio import Episode

    logging.info("Migrate {} to episode".format(filename))
    episode = Episode(config, show)
    audiofile = MP3(filename)
    episode.filename = filename
    episode.duration = round(float(_get_mp3_tag(audiofile, 'TLEN', 0)) / 1000)
    episode.duration_string = str(timedelta(seconds=episode.duration))
    filemtime = date.fromtimestamp(
        os.path.getmtime(filename)).strftime('%Y-%m-%d %H:%M')
    starttimestr = _get_mp3_tag(audiofile, 'TDRC', filemtime)
    episode.starttime = datetime.strptime(starttimestr,
                                          '%Y-%m-%d %H:%M').timetuple()
    episode.pubdate = time.strftime('%c', episode.starttime)
    episode.slug = os.path.join(
        show.slug,
        "{}_{}.mp3".format(slugify(episode.show.id),
                           time.strftime('%Y-%m-%d_%H-%M', episode.starttime)))
    basename = os.path.basename(filename)
    episode.name = _get_mp3_tag(audiofile, 'TIT2', basename[:-4])
    new_filename = os.path.join(show.filename, basename)
    if new_filename != filename:
        new_dirname = os.path.dirname(new_filename)
        if not os.path.exists(new_dirname):
            os.makedirs(new_dirname)
        shutil.move(filename, new_filename)
        episode.filename = new_filename
    episode.slug = os.path.join(show.slug, basename)
    episode.filesize = str(os.path.getsize(episode.filename))
    episode.mimetype = 'audio/mpeg'
    return episode
Ejemplo n.º 2
0
 def use_id3():
     audio = MP3(song_path, ID3=EasyID3)
     audio.clear()
     audio['title'] = song['name']
     audio['artist'] = song['artist']
     audio['album'] = song['album']
     audio.save()
Ejemplo n.º 3
0
def write_tags(musicPath, title, album):
    audio = MP3(musicPath, ID3=EasyID3)
    audio.clear()
    artist, musicname = get_artist_and_musicname_from_title(title)
    audio['title'] = musicname
    audio['artist'] = artist
    audio['album'] = album.strip()
    audio.save()
Ejemplo n.º 4
0
    def Load(self, path):
        """
        Supported file extensions:

            * For MPEG4: ``mp4``, ``aac``, ``m4a``
            * For MPEG3: ``mp3``, ``MP3``
            * For FLAC: ``flac``

        Args:
            path (str): path to the song file that shall be loaded

        Returns:
            *Nothing*

        Raises:
            TypeError: If path is not a string
            ValueError: If file not exist or file cannot be read.
            ValueError: If the file extension or file format is not supported
        """
        logging.debug("Analysing file from %s", path)
        if type(path) != str:
            raise TypeError("Path must be a string!")

        # do some filename-management
        self.path = self.fs.AbsolutePath(path)
        if not self.fs.IsFile(self.path):
            raise ValueError("File \"%s\" does not exist" % (self.path))

        # remenber the path for debugging
        self.extension = self.fs.GetFileExtension(self.path)

        # normalize the extension
        if self.extension in ["mp4", "aac", "m4a"]:
            self.ftype = "m4a"
        elif self.extension == "flac":
            self.ftype = "flac"
        elif self.extension in ["mp3", "MP3"]:
            self.ftype = "mp3"
        else:
            self.path = None
            raise ValueError("Unsupported file-extension \"%s\" of \"%s\"" %
                             (self.extension, path))

        logging.debug("Loading file of type %s from \"%s\"", self.ftype,
                      self.path)

        # open the file
        if self.ftype == "flac":
            self.file = FLAC(self.path)
        elif self.ftype == "mp3":
            self.file = MP3(self.path)
        elif self.ftype == "m4a":
            self.file = MP4(self.path)
        else:
            self.path = None
            raise ValueError("Unsupported file-type %s" % (self.ftype))
Ejemplo n.º 5
0
    def parse(self, file_path):
        hash = self.__get_hash(file_path)
        path = os.path.split(file_path)[1]
        extension = self.get_extension(file_path)

        if(extension == "MP3"):
            mp3 = MP3(file_path)
            return (AudioFileMetadata(self.__get_duration(mp3.info.length),
                self.__get_bitrate(mp3.info.bitrate),
                hash,
                path,
                extension))
        if(extension == "JPG"):
            img = Image.open(file_path)
            return ImageFileMetadata(hash, path, extension, img.size[0], img.size[1])
Ejemplo n.º 6
0
    def id3Info(self, filepath):
        #from time import time as systime
        #systime1 = systime()
        try:
            audio = MP3(filepath)
        except:
            return [
                None, 0, '', '', '',
                self.getTracklength(filepath), '', filepath
            ]
        #print(systime() - systime1)
        try:
            tracknum = audio["TRCK"][0]
        except:
            tracknum = 0
        if tracknum is not None:
            try:
                tracknum = int(tracknum.split('/')[0])
            except ValueError:
                tracknum = 0
            except:
                tracknum = int(tracknum)
        #print (audio["TIT2"][0]).encode('ascii', 'replace')
        try:
            songtitle = (audio["TIT2"][0])  #.encode('ascii', 'replace')
        except:
            songtitle = "Unknown Title"
        try:
            artist = audio["TPE1"][0]
        except:
            artist = "Unknown Artist"
        try:
            album = audio["TALB"][0]
        except:
            album = "Unknown Album"
        try:
            genre = audio["TCON"][0]
        except:
            genre = "None"

        tracklength = int(round(audio.info.length))
        m, s = divmod(tracklength, 60)
        tracklength = "%02i:%02i" % (m, s)
        filepath = "%s%s" % ("file://", filepath)
        return [
            None, tracknum, songtitle, artist, album, tracklength, genre,
            filepath
        ]
Ejemplo n.º 7
0
def read_music_info(path):
    """读取歌曲的tag信息。"""
    audio = MP3(path)
    basepath = os.path.splitext(path)[0]
    basename = os.path.split(basepath)[-1]
    musicname = '%s' % audio.get("TIT2", basename)
    artist = '%s' % audio.get("TPE1", "")
    album = '%s' % audio.get("TALB", "未知专辑")
    try:
        totalTimeValue = int(audio.info.length)
        totalTime = format_position_to_mmss(totalTimeValue)
    except:
        totalTime = Configures.ZeroTime
    if not artist:
        title = musicname
    else:
        title = connect_as_title(artist, musicname)
    return title, album, totalTime
Ejemplo n.º 8
0
    def _add_metadata(self, episode):
        if episode.filename is None:
            raise "filename is not set - you cannot add metadata to None"

        episode.description = 'Show: {show}<br>Date: {date}<br>Copyright: {year} <a href="{link_url}">{station}</a>'.format(
            show=episode.show.name,
            date=episode.pubdate,
            year=time.strftime('%Y', episode.starttime),
            station=episode.station.name,
            link_url=episode.link_url)

        config = Configuration()
        comment = config.comment_pattern % {
            'show': episode.show.name,
            'date': episode.pubdate,
            'year': time.strftime('%Y', episode.starttime),
            'station': episode.station.name,
            'link_url': episode.link_url
        }

        audiofile = MP3(episode.filename, ID3=ID3)
        # add ID3 tag if it doesn't exist
        try:
            audiofile.add_tags()
        except error:
            pass

        audiofile.tags.add(TIT2(encoding=2, text=[episode.name]))
        audiofile.tags.add(TDRC(encoding=2, text=[episode.pubdate]))
        audiofile.tags.add(TCON(encoding=2, text=['Podcast']))
        audiofile.tags.add(TALB(encoding=2, text=[episode.show.name]))
        audiofile.tags.add(TLEN(encoding=2, text=[episode.duration * 1000]))
        audiofile.tags.add(TPE1(encoding=2, text=[episode.station.name]))
        audiofile.tags.add(TCOP(encoding=2, text=[episode.station.name]))
        audiofile.tags.add(
            COMM(encoding=2, lang='eng', desc='desc', text=comment))
        audiofile.tags.add(TCOM(encoding=2, text=[episode.link_url]))
        self._add_logo(audiofile, episode.logo_url)
        audiofile.save()
Ejemplo n.º 9
0
def test_add_metadata(config, test_folder):
    import shutil
    from mutagenx.mp3 import MP3

    media_file = test_folder.join('mystation', 'myshow', 'myepisode.pm3')
    os.makedirs(os.path.dirname(str(media_file)))
    shutil.copy(os.path.join(os.path.dirname(__file__), 'testfile.mp3'), str(media_file))

    station = config.stations['dlf']
    show = Show(config, station, 'me', 'Me', 2)
    episode = Episode(config, show)
    episode.filename = str(media_file)
    recorder = Recorder()
    recorder._add_metadata(episode)

    audio = MP3(str(media_file))
    #assert 'tit' == audio['TIT2'].text[0]
    assert 'Podcast' == audio['TCON'].text[0]
    assert 'Deutschlandfunk' == audio['TPE1'].text[0]
    assert 'Deutschlandfunk' == audio['TCOP'].text[0]
    assert 'Me' == audio['TALB'].text[0]
    assert 'http://example.org/dlf' == audio['TCOM'].text[0]
    assert u'2000' == audio['TLEN'].text[0]
Ejemplo n.º 10
0
 def test_id3_indicates_mp3_not_tta(self):
     header = b"ID3 the rest of this is garbage"
     fileobj = io.BytesIO(header)
     filename = "not-identifiable.ext"
     self.failUnless(TrueAudio.score(filename, fileobj, header) <
                     MP3.score(filename, fileobj, header))
Ejemplo n.º 11
0
def _setAttribute(filePath, attributeName, attributeValue):
  id3File = MP3(filePath)
  id3File[attributeName] = attributeValue
  id3File.save()
Ejemplo n.º 12
0
 def getTracklength(self, filepath):
     tracklength = int(round(MP3(filepath).info.length))
     m, s = divmod(tracklength, 60)
     tracklength = "%02i:%02i" % (m, s)
     return tracklength
Ejemplo n.º 13
0
    def Load(self, path):
        """
        Supported file extensions for audio files:

            * For MPEG4: ``aac``, ``m4a``
            * For MPEG3: ``mp3``, ``MP3``
            * For FLAC: ``flac``

        Supported file extensions for video files:

            * For MPEG4: ``m4v`` (``mp4``)
            * For WebM: ``webm``

        The corner case of an ``mp4`` file gets not handled as video because it is not clear if it shall be handled as audio
        or video file.
        A warning gets written into the log and a ``ValueError`` exception raised.

        Args:
            path (str): path to the song file that shall be loaded

        Returns:
            *Nothing*

        Raises:
            TypeError: If path is not a string
            ValueError: If file not exist or file cannot be read.
            ValueError: If the file extension or file format is not supported
        """
        logging.debug("Analysing file from %s", path)
        if type(path) != str:
            raise TypeError("Path must be a string!")

        # do some filename-management
        self.path = self.fs.AbsolutePath(path)
        if not self.fs.IsFile(self.path):
            raise ValueError("File \"%s\" does not exist" % (self.path))

        # remember the path for debugging
        self.extension = self.fs.GetFileExtension(self.path)

        # normalize the extension
        if self.extension in ["mp4"]:
            logging.warning(
                "A file with extension \"mp4\" shall be loaded. It will be loaded as video."
            )
            self.ftype = "m4v"
        elif self.extension in ["webm"]:
            self.ftype = "webm"
        elif self.extension in ["aac", "m4a"]:
            self.ftype = "m4a"
        elif self.extension in ["m4v"]:
            self.ftype = "m4v"
        elif self.extension == "flac":
            self.ftype = "flac"
        elif self.extension in ["mp3", "MP3"]:
            self.ftype = "mp3"
        else:
            self.path = None
            raise ValueError("Unsupported file extension \"%s\" of \"%s\"" %
                             (self.extension, path))

        logging.debug("Loading file of type %s from \"%s\"", self.ftype,
                      self.path)

        # open the file
        if self.ftype == "flac":
            self.file = FLAC(self.path)
        elif self.ftype == "mp3":
            self.file = MP3(self.path)
        elif self.ftype == "m4a":
            self.file = MP4(self.path)
        elif self.ftype == "m4v":
            self.file = MP4(self.path)
        elif self.ftype == "webm":
            logging.warning("WebM only partially supported!")
            self.file = None
        else:
            self.path = None
            raise ValueError("Unsupported file-type %s" % (self.ftype))