Пример #1
0
            def check_meta(path):
                if entry.name.endswith(".mp3"):
                    audio = MP3(n)
                    try:
                        audio['album']
                        return True
                    except KeyError:
                        return False

                elif entry.name.endswith(".mp4"):
                    audio = MP4(n)
                    try:
                        audio['\xa9alb']
                        return True
                    except Exception:
                        return False
Пример #2
0
def movie17(channel):
    global timeout
    print("Button #17 was pushed!")
    os.system('killall omxplayer.bin')
    #omxc = Popen(['omxplayer', '-b', movie1])

    #Get video clip size and write it to global variable
    audio = MP4("/home/pi/Videos/clips/makerbuino.mp4")
    timeout = time.time() + int(audio.info.length)

    Popen(['omxplayer', '-b', "/home/pi/Videos/clips/makerbuino.mp4"])
    sleep(1)

    # Sending the data to thingspeak
    response = urllib2.urlopen(
        'https://api.thingspeak.com/update?api_key=LAHVIW9MF62TZET4&field1=17')
Пример #3
0
def movie3(channel):
    global timeout
    print("Button #3 was pushed!")
    os.system('killall omxplayer.bin')
    #omxc = Popen(['omxplayer', '-b', movie1])

    #Get video clip size and write it to global variable
    audio = MP4("/home/pi/Videos/clips/3-dashdot.mp4")
    timeout = time.time() + int(audio.info.length)

    Popen(['omxplayer', '-b', "/home/pi/Videos/clips/3-dashdot.mp4"])
    sleep(2)

    # Sending the data to thingspeak
    response = urllib2.urlopen(
        'https://api.thingspeak.com/update?api_key=RFXZ62G9U5SQAUY0&field1=3')
Пример #4
0
def movie5(channel):
    global timeout
    print("Button #5 was pushed!")
    os.system('killall omxplayer.bin')
    #omxc = Popen(['omxplayer', '-b', movie1])

    #Get video clip size and write it to global variable
    audio = MP4("/home/pi/Videos/clips/5-ozobot-evo.mp4")
    timeout = time.time() + int(audio.info.length)

    Popen(['omxplayer', '-b', "/home/pi/Videos/clips/5-ozobot-evo.mp4"])
    sleep(2)

    # Sending the data to thingspeak
    response = urllib2.urlopen(
        'https://api.thingspeak.com/update?api_key=H3LMV95MN0K3AGQC&field1=5')
Пример #5
0
def resolve_mp4_metadata(config: dict, track: Track, path: str,
                         cover: Optional[Cover]) -> None:
    tagger = MP4(path)
    tagger["\xa9nam"] = track.name
    tagger["\xa9alb"] = track.album.name
    tagger["\xa9ART"] = [artist.name for artist in track.artists]
    tagger["aART"] = [artist.name for artist in track.album.artists]
    tagger["trkn"] = [(track.track_number, 0)]
    tagger["disk"] = [(track.disc_number, 0)]
    if cover:
        imageformat = {
            "image/png": MP4Picture.FORMAT_PNG,
            "image/jpeg": MP4Picture.FORMAT_JPEG,
        }[cover.mime]
        tagger["covr"] = [MP4Picture(cover.data, imageformat=imageformat)]
    tagger.save()
Пример #6
0
def compare(music_file, metadata):
    """Check if the input music file title matches the expected title."""
    already_tagged = False
    try:
        if music_file.endswith('.mp3'):
            audiofile = EasyID3(music_file)
            # fetch track title metadata
            already_tagged = audiofile['title'][0] == metadata['name']
        elif music_file.endswith('.m4a'):
            tags = {'title': '\xa9nam'}
            audiofile = MP4(music_file)
            # fetch track title metadata
            already_tagged = audiofile[tags['title']] == metadata['name']
    except (KeyError, TypeError):
        pass
    return already_tagged
Пример #7
0
def tag_file(filename, metadata):
    image = None
    if metadata['artwork_url']:
        download_file('artwork.jpg', metadata['artwork_url'], silent=True)
    if os.path.isfile('artwork.jpg'): image = open('artwork.jpg', 'rb').read()
    if filename.endswith('.mp3'):
        audio = MP3(filename, ID3=ID3)
        audio.add_tags()
        if image:
            audio.tags.add(
                APIC(encoding=3,
                     mime='image/jpeg',
                     type=3,
                     desc=u'Cover',
                     data=image))
        audio.tags["TIT2"] = TIT2(encoding=3, text=metadata['title'])
        audio.tags["TPE1"] = TPE1(encoding=3, text=metadata['artist'])
        audio.tags["TDRC"] = TDRC(encoding=3, text=metadata['year'])
        audio.tags["TCON"] = TCON(encoding=3, text=metadata['genre'])
        audio.save()
    elif filename.endswith('.flac'):
        audio = FLAC(filename)
        audio.add_tags()
        if image:
            audio.tags.add(
                APIC(encoding=3,
                     mime='image/jpeg',
                     type=3,
                     desc=u'Cover',
                     data=image))
        audio.tags['title'] = metadata['title']
        audio.tags['artist'] = metadata['artist']
        audio.tags['year'] = metadata['year']
        audio.tags['genre'] = metadata['genre']
        audio.save()
    elif filename.endswith('.m4a'):
        audio = MP4(filename)
        audio.add_tags()
        covr = []
        if image: covr.append(MP4Cover(image, MP4Cover.FORMAT_JPEG))
        audio.tags['covr'] = covr
        audio.tags['title'] = metadata['title']
        audio.tags['artist'] = metadata['artist']
        audio.tags['year'] = metadata['year']
        audio.tags['genre'] = metadata['genre']
        audio.save()
    if os.path.isfile('artwork.jpg'): os.remove('artwork.jpg')
    def as_m4a(self, path, metadata, cached_albumart=None):
        """
        Apply metadata on FLAC media files.

        Parameters
        ----------
        path: `str`
            Path to the media file.

        metadata: `dict`
            Metadata (standardized) to apply to the media file.

        cached_albumart: `bool`
            An albumart image binary. If passed, the albumart URL
            present in the ``metadata`` won't be downloaded or used.
        """

        logger.debug('Writing M4A metadata to "{path}".'.format(path=path))
        # For supported m4a tags:
        # https://github.com/quodlibet/mutagen/blob/master/mutagen/mp4/__init__.py
        # Look for the class named `MP4Tags` in the linked source file
        audiofile = MP4(path)
        self._embed_basic_metadata(audiofile,
                                   metadata,
                                   "m4a",
                                   preset=M4A_TAG_PRESET)
        if metadata["year"]:
            audiofile[M4A_TAG_PRESET["year"]] = metadata["year"]
        provider = metadata["provider"]
        audiofile[
            M4A_TAG_PRESET["comment"]] = metadata["external_urls"][provider]
        if metadata["lyrics"]:
            audiofile[M4A_TAG_PRESET["lyrics"]] = metadata["lyrics"]
        # Explicit values: Dirty: 4, Clean: 2, None: 0
        audiofile[M4A_TAG_PRESET["explicit"]] = (
            4, ) if metadata["explicit"] else (2, )
        try:
            if cached_albumart is None:
                cached_albumart = urllib.request.urlopen(
                    metadata["album"]["images"][0]["url"]).read()
            audiofile[M4A_TAG_PRESET["albumart"]] = [
                MP4Cover(cached_albumart, imageformat=MP4Cover.FORMAT_JPEG)
            ]
        except IndexError:
            pass

        audiofile.save()
Пример #9
0
 def add_meta_data(self, file_name, name, band, album, year, track_number,
                   model):
     # Use mutagen to add metadata
     # https://mutagen.readthedocs.io/en/latest/
     # https://stackoverflow.com/questions/44895095/is-it-possible-to-add-id3-tags-to-m4a-files-using-mutagen
     if file_name.endswith('.m4a'):
         try:
             model.log("Adding metadata")
             tags = MP4(file_name).tags
             tags["\xa9nam"] = name
             tags["\xa9ART"] = band
             tags["\xa9alb"] = album
             tags["\xa9day"] = year
             tags.save(file_name)
         except:
             model.log("Failed to add meta data, " + file_name +
                       " may be corrupt")
Пример #10
0
    def get_primary_image(self):
        try:
            tag = MP4(self["~filename"])
        except Exception:
            return

        for cover in tag.get("covr", []):

            if cover.imageformat == MP4Cover.FORMAT_JPEG:
                mime = "image/jpeg"
            elif cover.imageformat == MP4Cover.FORMAT_PNG:
                mime = "image/png"
            else:
                mime = "image/"

            f = get_temp_cover_file(cover)
            return EmbeddedImage(f, mime)
def addCoverToM4B(filename, albumart):
    """add cover to m4a"""

    audio = MP4(filename)
    data = open(albumart, "rb").read()

    covr = []
    if albumart.endswith("png"):
        covr.append(MP4Cover(data, MP4Cover.FORMAT_PNG))
    else:
        covr.append(MP4Cover(data, MP4Cover.FORMAT_JPEG))

    audio.tags["covr"] = covr

    audio.save()

    return True
Пример #12
0
def addMetadata(fileName,thumbnail,title,artist,album):
    """ Add metadata and thumbnail to mp3 and mp4 files (TODO for mp4).
    
    Parameters:
    ----------
    fileName : str
        Source file with complete path.
    thumbnail : str
        Name of the thumbnail image file with full path.
    title : str
    artist : str
    album : str
    
    Usage:
    -----
    utils.convertFileFormat(source,target,deleteSource=True)
    
    Returns:
    -------
    title : str
    artist : str
    album : str
    """
    
    if ('.mp3' in fileName):
        audio = MP3(fileName,ID3=ID3)
        audio.tags.add(APIC(mime='image/jpeg',type=3,desc=u'Cover',data=open(thumbnail,'rb').read()))
        audio.save()
        os.remove(thumbnail)
        
        # ADD TITLE AND ALBUM NAME
        audio = EasyID3(fileName)
        audio['title'] = title
        audio['artist'] = artist
        audio['album'] = album
        audio.save()
    elif ('.mp4' in fileName):
        video = MP4(fileName)
        tags = video.tags
        tags['\xa9nam'] = title
        tags['\xa9ART'] = artist
        tags['\xa9alb'] = album
        with open(thumbnail,'rb') as f:
            tags["covr"] = [MP4Cover(f.read(), imageformat=MP4Cover.FORMAT_JPEG)]
        tags.save(fileName)
        os.remove(thumbnail)
Пример #13
0
def id3_mp4_createSongFromPath(song):

    audio = MP4(song[EnumSong.PATH])

    # print all keys, but only the first 70 chars
    #for key in audio.keys():
    #    print ("%s => %s"%(key,audio[key]))[:70]

    getTag(song, audio, EnumSong.ALBUM, "\xA9alb")
    getTag(song, audio, EnumSong.ARTIST, "\xA9ART")
    getTag(song, audio, EnumSong.TITLE, "\xA9nam")
    getTag(song, audio, EnumSong.GENRE, "\xA9gen")

    getTag_TupleOfInt(song, audio, EnumSong.SONGINDEX, "trkn")

    song[EnumSong.LENGTH] = int(audio.info.length)
    song[EnumSong.BITRATE] = int(audio.info.bitrate)
Пример #14
0
def add_tags(filename, json_data, playlist_name):
    audio = MP4(filename)
    audio['\xa9nam'] = str(json_data['song'])
    audio['\xa9ART'] = str(json_data['primary_artists'])
    audio['\xa9alb'] = str(json_data['album'])
    audio['aART'] = str(json_data['singers'])
    audio['\xa9wrt'] = str(json_data['music'])
    audio['desc'] = str(json_data['starring'])
    audio['\xa9gen'] = str(playlist_name)
    audio['\xa9day'] = str(json_data['year'])
    audio['cprt'] = str(json_data['label'])
    cover_url = json_data['image'][:-11] + '500x500.jpg'
    fd = urllib.request.urlopen(cover_url)
    cover = MP4Cover(fd.read(), getattr(MP4Cover, 'FORMAT_PNG' if cover_url.endswith('png') else 'FORMAT_JPEG'))
    fd.close()
    audio['covr'] = [cover]
    audio.save()
Пример #15
0
def set_metadata(track, filename):
    if not filename.suffix == '.m4a':
        # flac not supported yet
        return
    f = MP4(str(filename))
    f.tags.clear()
    f.tags['\xa9ART'] = ', '.join([a.name for a in track.artists
                                   ]) if track.artists else track.artist.name
    f.tags['\xa9nam'] = "{}{}".format(
        track.name, " ({})".format(track.version) if track.version else "")
    f.tags['\xa9alb'] = track.album.name
    if track.album.release_date:
        f.tags['\xa9day'] = str(track.album.release_date.year)
    with requests.get(track.album.picture(320, 320)) as result:
        if result.ok:
            f.tags['covr'] = [MP4Cover(result.content)]
    f.save()
Пример #16
0
def get_track_info(filename):
    artwork = pict = None
    artist = track = album = None
    duration = 0
    if filename[-3:].lower() == 'mp3':
        try:
            audio = ID3(filename)
            if audio.get('APIC:') is not None:
                pict = audio.get('APIC:').data
            if audio.get('APIC:Cover') is not None:
                pict = audio.get('APIC:Cover').data
            if pict is not None:
                im = Image.open(BytesIO(pict)).convert('RGB')
                buff = BytesIO()
                im.save(buff, format='jpeg')
                artwork = base64.b64encode(buff.getvalue()).decode('utf-8')
            if audio.get('TPE1') is not None:
                artist = audio['TPE1'].text[0]
            if audio.get('TIT2') is not None:
                track = audio['TIT2'].text[0]
            if audio.get('TALB') is not None:
                album = audio['TALB'].text[0]
        except ID3NoHeaderError:
            pass
        duration = MP3(filename).info.length
    elif filename[-3:].lower() == 'm4a':
        audio = MP4(filename)
        if audio.get("covr") is not None:
            pict = audio.get("covr")[0]
            im = Image.open(BytesIO(pict)).convert('RGB')
            buff = BytesIO()
            im.save(buff, format='jpeg')
            artwork = base64.b64encode(buff.getvalue()).decode('utf-8')
        if audio.get('\xa9ART') is not None:
            artist = audio.get('\xa9ART')[0]
        if audio.get('\xa9nam') is not None:
            track = audio.get('\xa9nam')[0]
        if audio.get('\xa9alb') is not None:
            album = audio.get('\xa9alb')[0]
        duration = audio.info.length
    if artwork == None:
        artwork = base64.b64encode(open('./static/record.jpg', 'rb').read()).decode()
    if (artist, track, album) == (None, None, None):
        artist = filename
    return artwork, artist, track, album, duration
Пример #17
0
def addtags(filename, json_data):
    try:
        audio = MP4(filename)
        audio['\xa9nam'] = unicode(json_data['song'])
        audio['\xa9ART'] = unicode(json_data['primary_artists'])
        audio['\xa9alb'] = unicode(json_data['album'])
        audio['aART'] = unicode(json_data['singers'])
        audio['\xa9wrt'] = unicode(json_data['music'])
        audio['\xa9gen'] = unicode(json_data['language'])
        audio['purl'] = unicode(json_data['album_url'])
        audio['\xa9day'] = unicode(json_data['year'])
        audio['\xa9cmt'] = 'starring : {}'.format(
            unicode(json_data['starring']))
        audio['desc'] = parseHastags(json_data)
        cover_url = json_data['image'][:-11] + '500x500.jpg'
        fd = urllib.request.urlopen(cover_url)
        cover = MP4Cover(
            fd.read(),
            getattr(
                MP4Cover,
                'FORMAT_PNG' if cover_url.endswith('png') else 'FORMAT_JPEG'))
        fd.close()
        audio['covr'] = [cover]
        audio.save()
        #‘\xa9lyr’ – lyrics
    except:
        os.rename(filename, filename[:-3] + 'mp3')
        filename = filename[:-3] + 'mp3'
        try:
            audio = ID3(filename)
        except ID3NoHeaderError:
            audio = ID3()

        audio.add(TPE1(encoding=3, text=unicode(json_data['singers'])))
        audio.save(filename)
        audio = EasyID3(filename)
        audio['title'] = unicode(json_data['song'])
        audio['albumartist'] = unicode(json_data['primary_artists'])
        audio['album'] = unicode(json_data['album'])
        #audio['aART'] = unicode(json_data['singers'])
        audio['copyright'] = unicode(json_data['music'])
        #audio['copyright'] = unicode(json_data['starring'])
        audio['genre'] = unicode(json_data['label'])
        audio['date'] = unicode(json_data['year'])
        audio.save()
Пример #18
0
    def _update_metadata_mp4(self,file_path,metadata):
         # print 'updating metadata'

         audio = MP4(file_path)
#         print metadata
         cover = metadata[5].decode('utf8')
         fd = urllib.urlopen(cover)

         covr = MP4Cover(fd.read(), getattr(
            MP4Cover,
            'FORMAT_PNG' if cover.endswith('png') else 'FORMAT_JPEG'
        ))
         fd.close() # always a good thing to do
         audio['covr'] = [covr] # make sure it's a list
         audio["\xa9nam" ] = metadata[0]# name
         audio["\xa9ART" ] = metadata[4]# artist
         audio["\xa9alb" ] = metadata[3]# album
         audio.save()
Пример #19
0
def EstablecerTags(archivo, lista_tags):
    """
    Recibe una lista con el formato [Nombre, Artista, Album, Tracknumber(int), Albumyear, Tracktotal (int), Link Album, Duracion, LinkYoutube]
    """
    tags_cancion = MP4(archivo)
    tags_cancion['\xa9nam'] = lista_tags[0]
    tags_cancion['\xa9ART'] = lista_tags[1]
    tags_cancion['\xa9grp'] = lista_tags[1]
    tags_cancion['\xa9alb'] = lista_tags[2]
    tags_cancion['trkn'] = [(lista_tags[3], lista_tags[5])]
    tags_cancion['\xa9day'] = lista_tags[4]
    tags_cancion['\xa9cmt'] = lista_tags[8]
    if not lista_tags[6]:
        fd = urllib.urlopen(lista_tags[6])
        tags_cancion['covr'] = [MP4Cover(fd.read(), MP4Cover.FORMAT_JPEG)]
        fd.close()
    tags_cancion.save()
    return 1
Пример #20
0
def get_length(file_list):
    from mutagen.mp4 import MP4
    total_length = 0
    # f_name = ''
    for filePath in file_list:
        try:
            if filePath.endswith('.mp4'):
                mp4 = MP4(filePath)
                total_length = total_length + mp4.info.length
                # print(length.info.length)
                # print(os.path.getsize(filePath))
                # print(total_length)
                # f_name = filePath
        except:
            # print(f_name)
            continue
    # print(f_name)
    return total_length
Пример #21
0
    def write_to_mp4():
        """Add metadata to MP4 file."""
        # NOTE Metadata for MP4 will fail to write if any error (esp. with artwork) occurs
        audio = MP4(os.path.join(directory, song_filename))
        audio.add_tags()
        audio.tags["\xa9alb"] = song_properties["album"]
        audio.tags["\xa9ART"] = song_properties["artist"]
        audio.tags["\xa9nam"] = song_properties["song"]
        audio.tags["\xa9gen"] = song_properties["genre"]
        # Only add a cover if the response was ok and the header of the
        # response content is that of a JPEG image. Source:
        # https://www.file-recovery.com/jpg-signature-format.htm.
        if valid_artwork():
            audio.tags["covr"] = [
                MP4Cover(response.content, imageformat=MP4Cover.FORMAT_JPEG)
            ]

        audio.save()
Пример #22
0
def file_attributes(path, name, video):
    name = regex(name)
    options = video.streams.filter(
        type="audio", file_extension="mp4").order_by("bitrate").first()
    # downloads the file to folder, prepends it with playlist number
    name = name.replace("_.mp4", ".mp4")
    options.download(
        path,
        skip_existing=True,
        filename=name,
    )
    name = os.path.join(path, name + ".mp4")
    song = MP4(name)
    song["\xa9nam"] = video.title  # video title
    song["\xa9ART"] = video.author  # video author (channel video came from)
    song["\xa9alb"] = os.path.basename(os.path.dirname(name))
    song.save()  # save changes to video
    return name
Пример #23
0
    def setM4AMetadata(self):
        self.startingProcessing.emit()
        tags = MP4(f"{self.parent.album()}/{self.parent.title()}.m4a").tags
        tags['\xa9nam'] = self.parent.title()
        tags['\xa9alb'] = self.parent.album()
        tags['\xa9ART'] = self.parent.artist()
        tags['aART'] = self.parent.artist()
        tags['\xa9wrt'] = self.parent.artist()
        tags['\xa9day'] = self.parent.year()
        tags['trkn'] = [self.parent.trackIndex()]

        with open(self.parent.albumArtPath(), 'rb') as albumart:
            tags['covr'] = [MP4Cover(albumart.read(), MP4Cover.FORMAT_PNG)]

        tags.save(f"{self.parent.album()}/{self.parent.title()}.m4a")


        self.allDone.emit()
Пример #24
0
def retag(filename, movie):
    '''Re-tags an MP4 file with information from the movie record


  Parameters:

    filename (str): The full path to the movie file to be re-tagged

    movie (obj): An object returned by the TMDB API implementation containing
      all fields required to retag the movie

  '''

    logger.info("Tagging file: %s" % filename)
    hd_tag = _hd_tag(filename)
    video = MP4(filename)

    try:
        video.delete()
        logger.debug("Successfuly deleted currently existing tags on file")
    except IOError:
        logger.warn("Unable to clear original tags, attempting to proceed...")

    video["\xa9nam"] = movie.title
    video["desc"] = movie.tagline
    video["ldes"] = movie.overview
    video["\xa9day"] = movie.release_date
    video["stik"] = [9]  # Movie iTunes category
    video["hdvd"] = [hd_tag]
    video["\xa9gen"] = [k['name'] for k in movie.genres]
    video["----:com.apple.iTunes:iTunMOVI"] = _make_apple_plist(movie)
    video["----:com.apple.iTunes:iTunEXTC"] = _us_certification(movie)

    if hasattr(movie, 'poster_path'):
        bindata = _get_image(movie)
        if movie.poster_path.endswith('.png'):
            video["covr"] = [MP4Cover(bindata, MP4Cover.FORMAT_PNG)]
        else:
            video["covr"] = [MP4Cover(bindata, MP4Cover.FORMAT_JPEG)]
        logger.info('Finally saving tags to file...')

    video.save()

    logger.info("Tags written successfully")
Пример #25
0
def pandoraDownloader():

    # Build the song's path - remove any invalid characters
    song_path = save_template.format(
        station=re.sub(u'[<>\*:\\/\"|?]', '',
                       request.form['station'].encode('utf-8')),
        artist=re.sub(u'[<>\*:\\/\"|?]', '',
                      request.form['artist'].encode('utf-8')),
        album=re.sub(u'[<>\*:\\/\"|?]', '',
                     request.form['album'].encode('utf-8')),
        title=re.sub(u'[<>\*:\\/\"|?]', '',
                     request.form['title'].encode('utf-8'))).decode('utf-8')

    # check to see if the file has been downloaded before!
    if os.path.exists(song_path):
        print('Song found already')
        return jsonify(status='alreadyDownloaded')

    else:
        print('Downloading "' + request.form['title'].encode('utf-8') + '"')

        # Create the directories if they don't exist
        if not os.path.isdir(os.path.split(song_path)[0]):
            os.makedirs(os.path.split(song_path)[0])

        # Download the song
        urllib.urlretrieve(request.form['url'], song_path)

        song = MP4(song_path)

        song['\xa9nam'] = [request.form['title'].encode('utf-8')]
        song['\xa9ART'] = [request.form['artist'].encode('utf-8')]
        song['\xa9alb'] = [request.form['album'].encode('utf-8')]

        albumArtRequest = urllib.urlopen(request.form['albumArt'])
        albumArt = MP4Cover(albumArtRequest.read())
        albumArtRequest.close()

        song['covr'] = [albumArt]

        song.save()

        print('Download Complete!')
        return jsonify(status='success')
Пример #26
0
def library_cleaner(library_path):
    # the below regex is used to filter out characters that Windows doesn't like in directory names
    folder_regex = re.compile(r'\*|\\|\||<|>|/|\?|:|"')
    # program starts by cycling through all of the artist subfolders in the main music folder
    for artist_name in os.listdir(library_path):
        # the artist folder path is obtained by combining the main music folder path with the artist name
        artist_folder = library_path + '/' + artist_name
        # the program then iterates through all of the albums in the artist's folder
        for album_name in os.listdir(artist_folder):
            album_folder = artist_folder + '/' + album_name
            # this determines if the first file in the folder is an audio file or not. TODO - could be cleaned up to actually iterate through items in folder
            if os.listdir(album_folder):
                if Path(album_folder + '/' + os.listdir(album_folder)[0]
                        ).suffix != '.flac' or '.mp3' or '.m4a':
                    first_track_filename = os.listdir(album_folder)[-1]
                else:
                    first_track_filename = os.listdir(album_folder)[0]
                # if the file is an mp3
                if Path(first_track_filename).suffix == '.mp3':
                    first_track = ID3(album_folder + '/' +
                                      first_track_filename)
                    real_album_name = re.sub(folder_regex, '',
                                             first_track['TALB'].text[0])
                    print(f'Renamed {album_name} to {real_album_name}.')
                    os.rename(album_folder,
                              os.path.join(artist_folder, real_album_name))
                # if the file is a flac
                if Path(first_track_filename).suffix == '.flac':
                    first_track = FLAC(album_folder + '/' +
                                       first_track_filename)
                    real_album_name = re.sub(folder_regex, '',
                                             first_track['album'][0])
                    print(f'Renamed {album_name} to {real_album_name}.')
                    os.rename(album_folder,
                              os.path.join(artist_folder, real_album_name))
                # if the file is an m4a
                if Path(first_track_filename).suffix == '.m4a':
                    first_track = MP4(album_folder + '/' +
                                      first_track_filename)
                    real_album_name = re.sub(folder_regex, '',
                                             str(first_track['\xa9alb'][0]))
                    print(f'Renamed {album_name} to {real_album_name}.')
                    os.rename(album_folder,
                              os.path.join(artist_folder, real_album_name))
def mixTime(default_path, save_path, tts_path, lecture_trim_path):
    # slide에서 숫자만 떼놓는 부분
    data_pd = pd.read_csv(save_path, header=None, index_col=None, names=None)
    data_np = pd.DataFrame.to_numpy(data_pd)
    data_string = ""
    data_list = []
    for i in data_np[1:, 2]:
        data_string = i
        numbers = re.sub(r'[^0-9]', '', data_string)
        data_list.append(numbers)

    # csv 파일에 tts 추가한 시간 기록한 셀 추가
    mix_time_list = []
    time_csv = pd.read_csv(save_path)

    tts_list = os.listdir(tts_path)
    tts_list = [
        tts_file for tts_file in tts_list if tts_file.endswith(".mp3")
    ]  # tts 가져오기
    tts_list.sort()

    lec_list = os.listdir(lecture_trim_path)
    lec_list = [
        lec_file for lec_file in lec_list if lec_file.endswith(".mp4")
    ]  # lec 가져오기
    lec_list.sort()

    mix_time = 0.0
    mix_time_list.append(mix_time)

    for i, j in zip(range(len(time_csv["slide"]) - 1), data_list):
        tts_list[i] = MP3(default_path + "tts/" + "tts_" + j +
                          ".mp3").info.length
        lec_list[i] = MP4(default_path + "lecture_trim/" + "lec_" +
                          set_Filenum_of_Name(i + 1) + ".mp4").info.length

        mix_time = mix_time + tts_list[i] + lec_list[i]
        mix_time_list.append(mix_time)

        print(
            set_Filenum_of_Name(i + 1) +
            "번째 tts+lec MP3 mixed time csv에 기록 완료\n")

    return mix_time_list
Пример #28
0
    def tag(self) -> None:
        if self.filepath is None:
            raise AttributeError(f'Filepath of "{self.title}" not set')

        if self.ext == "flac":
            audio = FLAC(self.filepath)
            for k, v in self.__dict__.items():
                # TODO: fix composer glitch where it displays as list
                if (
                    k.upper() in ["ARTIST", "COMPOSER", "GENRE", "ALBUMARTIST"]
                    and type(v) is list
                ):
                    audio[k.upper()] = ", ".join(v)
                elif k not in ["filepath", "cover_url", "pos", "length"]:
                    audio[k] = str(v)

            audio.save()
        elif self.ext == "m4a":
            audio = MP4(self.filepath)
            for k, v in self.__dict__.items():
                if (
                    k
                    not in [
                        "filepath",
                        "cover_url",
                        "pos",
                        "length",
                        "date",
                        "label",
                        "url",
                        "tracktotal",
                        "disctotal",
                        "artist",
                    ]
                    and v is not None
                ):
                    audio[_mp4_keys[k]] = v
                elif k in ["artist"]:
                    audio[_mp4_keys[k]] = ", ".join(v)

            audio[_mp4_keys["tracknumber"]] = [(self.tracknumber, self.tracktotal)]
            audio[_mp4_keys["discnumber"]] = [(self.discnumber, self.disctotal)]
            audio["covr"] = self.images
            audio.save()
Пример #29
0
	def populate_from_mp4_tags(self, file_path, file_name):
		"""
		Populate record from m4a/mp4 data.
		"""
		a = MP4(file_path)
		tag = a.tags
		
		# TODO: Make this more verbose to the user.
		if audio.info.length > settings.MAX_SONG_LENGTH:
			raise Exception, "Audio is longer than maximum allowed."
		
		if audio.info.length < settings.MIN_SONG_LENGTH:
			raise Exception, "Audio is shorter than minimum allowed."
			
		try:
			
			#print tag
			# Map MP4 tags to columns in the Song table.
			try:
				self.title = tag['title'][0]
			except KeyError:
				# No tag for title found, use file name.
				self.title = file_name
			
			try:
				self.artist = tag['artist'][0]
			except KeyError:
				pass
			
			try:
				self.album = tag['album'][0]
			except KeyError:
				pass
			
			try:
				self.genre = tag['genre'][0]
			except KeyError:
				pass
			
			#TODO: Handle track number and disc number from mp4 tags.
			
		except:
			# Invalid headers. Just use the file name as the title.
			self.title = file_name
Пример #30
0
def embed_m4a(music_file, meta_tags):
    """Embed metadata to M4A files."""
    # Apple has specific tags - see mutagen docs -
    # http://mutagen.readthedocs.io/en/latest/api/mp4.html
    tags = {'album': '\xa9alb',
            'artist': '\xa9ART',
            'date': '\xa9day',
            'title': '\xa9nam',
            'originaldate': 'purd',
            'comment': '\xa9cmt',
            'group': '\xa9grp',
            'writer': '\xa9wrt',
            'genre': '\xa9gen',
            'tracknumber': 'trkn',
            'albumartist': 'aART',
            'disknumber': 'disk',
            'cpil': 'cpil',
            'albumart': 'covr',
            'copyright': 'cprt',
            'tempo': 'tmpo'}

    audiofile = MP4(music_file)
    audiofile[tags['artist']] = meta_tags['artists'][0]['name']
    audiofile[tags['albumartist']] = meta_tags['artists'][0]['name']
    audiofile[tags['album']] = meta_tags['album']['name']
    audiofile[tags['title']] = meta_tags['name']
    audiofile[tags['tracknumber']] = [(meta_tags['track_number'],
                                       meta_tags['total_tracks'])]
    audiofile[tags['disknumber']] = [(meta_tags['disc_number'], 0)]
    audiofile[tags['date']] = meta_tags['release_date']
    audiofile[tags['originaldate']] = meta_tags['release_date']
    if meta_tags['genre']:
        audiofile[tags['genre']] = meta_tags['genre']
    if meta_tags['copyright']:
        audiofile[tags['copyright']] = meta_tags['copyright']
    try:
        albumart = urllib.request.urlopen(meta_tags['album']['images'][0]['url'])
        audiofile[tags['albumart']] = [MP4Cover(
            albumart.read(), imageformat=MP4Cover.FORMAT_JPEG)]
        albumart.close()
    except IndexError:
        pass
    audiofile.save()
    return True
Пример #31
0
    def load(self, filename):
		MP4.load(self,filename)
		self.tags.__class__ = EasyMP4Tags
Пример #32
0
 def test_score(self):
     fileobj = open(self.filename)
     header = fileobj.read(128)
     self.failUnless(MP4.score(self.filename, fileobj, header))