示例#1
0
文件: shout.py 项目: dravog7/PyCast
    def getNextSong(self):
        try:
            fileName = self.songSource.nextSong()  # get next song filename
            self.fd = open(fileName, 'rb')
            self.file_size = os.path.getsize(fileName)
            # if there is valid ID3 data, read it out of the file first,
            # so we can skip sending it to the client
            try:
                self.id3 = id3reader.Reader(self.fd)
                if isinstance(
                        self.id3.header.size, int
                ) and self.id3.header.size < self.file_size:  # read out the id3 data
                    self.fd.seek(self.id3.header.size + 1, os.SEEK_SET)
                    log.debug("Reading %d bytes of ID3: %d",
                              self.id3.header.size, self.fd.tell())
            except id3reader.Id3Error:
                self.id3 = None
            self.metadata = self.make_metadata()

        except StopIteration:
            fileName = None
            self.fd = None
        except IOError:
            self.fd = None
        log.debug("getting next song: %s", fileName)
示例#2
0
def GetTrackInfo(filePath):

    global pauseOnError
    global pauseOnUnicode
    global found
    global tagError
    global lengthError
    global unicodeError
    global filePathError
    global corruptError
    global windowsError5
    global windowsError

    length = 0
    title = ""
    artist = ""
    album = ""
    genre = ""

    # Construct a reader from a file or filename.
    id3r = id3reader.Reader(filePath)
    try:
        op = 'retrieving length'
        f = codecs.open(filePath, 'rb')
        i = MP3Info.MP3Info(f)
        # length = i.mpeg.total_time
        length = i.mpeg.length
        op = 'retrieving title'
        title = id3r.getValue(u'title')
        op = 'retrieving artist'
        artist = id3r.getValue(u'performer')
        op = 'retrieving album'
        album = id3r.getValue(u'album')
        op = 'retrieving genre'
        genre = id3r.getValue(u'genre')

    except UnicodeEncodeError:
        unicodeError = unicodeError + 1
        try:
            print "Error with Unicode in %s while %s" % (filePath, op)
            if pauseOnUnicode == 'true':
                raw_input("Press ENTER to continue...")
        except UnicodeEncodeError:
            print " unprintable filename"
            if pauseOnUnicode == 'true':
                raw_input("Press ENTER to continue...")
    except:
        try:
            if op == 'retrieving length':
                lengthError = lengthError + 1
            print "Unhandled Exception in %s while %s" % (filePath, op)
            if pauseOnError == 'true':
                raw_input("Press ENTER to continue...")
        except UnicodeEncodeError:
            unicodeError = unicodeError + 1
            print " unprintable filename"
            if pauseOnError == 'true':
                raw_input("Press ENTER to continue...")

    return length, title, artist, album, genre
示例#3
0
def print_mp3_file_details(mp3_filename):
    id3r = id3reader.Reader(mp3_filename)
    print mp3_filename
    print "album:     " + str(id3r.getValue('album'))
    print "performer: " + str(id3r.getValue('performer'))
    print "title:     " + str(id3r.getValue('title'))
    print "year:      " + str(id3r.getValue('year'))
    print hashlib.sha256(open(mp3_filename, "r").read()).hexdigest()[0:16]
示例#4
0
    def _getID3Name(self, old_name):
        id3r = id3reader.Reader(old_name)

        track_number = id3r.getValue('track') or "0"
        track_number = track_number.split("/")[0]
        title = id3r.getValue('title') or "No title"
        title = title.strip()

        return self.to_ascii("%s %s.mp3" % (track_number.zfill(2), title))
示例#5
0
 def useId3reader(self, songPath):
     id3r = id3reader.Reader(songPath)
     print self.info
     if id3r.getValue("title"):
         self.info["name"] = id3r.getValue("title")
     if id3r.getValue("performer"):
         self.info["singer"] = id3r.getValue("performer")
     if id3r.getValue("album"):
         self.info["album"] = id3r.getValue("album")
def extract_year(s, files):
    directory_name = s
    years = [int(s) for s in s.split() if s.isdigit() and len(s) == 4]
    if len(years) > 0:
        return min(years)
    else:
        for file in files:
            if file.endswith("mp3") or file.endswith("wma"):
                id3r = id3reader.Reader("%s/%s" % (directory_name, file))
                if id3r.getValue('year'):
                    return id3r.getValue('year')
def extract_artist(s, files):
    directory_name = s
    artist_name = s.split("-")
    if len(artist_name) > 0:
        return artist_name[0].split("/")[-1]
    else:
        for file in files:
            if file.endswith("mp3") or file.endswith("wma"):
                id3r = id3reader.Reader("%s/%s" % (directory_name, file))
                if id3r.getValue('artist'):
                    return id3r.getValue('artist')
示例#8
0
    def _getID3Name(self, old_name):
        id3r = id3reader.Reader(old_name)

        separador = "-"
        track_artist = id3r.getValue('performer')
        track_artist = track_artist
        title = id3r.getValue('title') or "No title"
        title = title.strip()
        track_artist = replace_illegal_chars(track_artist)
        title = replace_illegal_chars(title)

        return self.to_ascii("%s %s %s.mp3" % (track_artist, separador, title))
def extract_album(s, files):
    directory_name = s
    artist_name = s.split("-")
    if len(artist_name) > 0:
        return artist_name[-1].replace(" (Forró em vinil)", "").replace(
            " (forró em vinil)", "").replace(" (forro em vinil)", "").strip()
    else:
        for file in files:
            if file.endswith("mp3") or file.endswith("wma"):
                id3r = id3reader.Reader("%s/%s" % (directory_name, file))
                if id3r.getValue('album'):
                    return id3r.getValue('album')
def id3_sort_key(mp3_path):
    """Create the sort key for an MP3 file.
    """
    id3r = id3reader.Reader(mp3_path)
    return (
        get_value(id3r, 'performer'),
        get_value(id3r, 'year'),
        get_value(id3r, 'album'),
        get_track(id3r),
        get_value(id3r, 'title'),
        # Provide the original path as a fallback for MP3s with missing or non-unique ID3 tags.
        mp3_path,
    )
示例#11
0
    def __init__(self, file):
        self.title = self.artist = self.track = self.year = \
                     self.comment = self.composer = self.album = \
                     self.disc = self.genre = self.encoder = None

        id3 = id3reader.Reader(file)
        if id3 and id3.frames and id3.frames != {}:
            self.title = id3.getValue('title')
            self.artist = id3.getValue('artist')
            self.track = id3.getValue('track')
            self.year = id3.getValue('year')
            self.comment = id3.getValue('comment')
            self.album = id3.getValue('album')
            self.genre = id3.getValue('genre')
            if self.genre and self.genre[0] == '(' and self.genre[-1] == ')':
                genres = self.num_regex.findall(self.genre)
                if len(genres) > 0:
                    try:
                        # Force to single value even if multiple
                        self.genre = id3reader.genres[int(genres[0])]
                    except IndexError:
                        self.genre = ""
                else:
                    self.genre = ""
            self.composer = id3.getValue('composer')
            self.disc = id3.getValue('disc')
            self.encoder = id3.getValue('encoder')

        mpeg = None
        if id3 and id3.header and id3.header.majorVersion and id3.header.majorVersion >= 2:
            # ID3v2 size (header_size) doesn't include 10 bytes of header
            mpeg = MPEG(file, seekstart=id3.header.size+10)
        else:
            # Header better be near the beginning if there is no ID3v2
            mpeg = MPEG(file)

        if mpeg:
            if mpeg.total_time > 0:
                self.total_time = mpeg.total_time
                self.filesize = mpeg.filesize2
                self.bitrate = int(mpeg.bitrate)
                self.samplerate = mpeg.samplerate/1000
                self.mode = mpeg.mode
                self.mode_extension = mpeg.mode_extension
            else:
                self.total_time = 0
                self.filesize = mpeg.filesize2
                self.bitrate = "unknown"
                self.samplerate = "unknown"
                self.mode = ""
                self.mode_extension = ""
示例#12
0
def ScanMusic(songTitle='', performer='', album='', directory='./music'):

    # Use OS to access input directory
    os.chdir(directory)

    # Read all files from designated music directory
    mp3Files = []
    for localFile in glob.glob("*.mp3"):
        mp3Data = id3reader.Reader(localFile)
        mp3Files.append({
            'file': localFile,
            'title': str(mp3Data.getValue('title')),
            'artist': str(mp3Data.getValue('performer')),
            'album': str(mp3Data.getValue('album'))
        })

    if (len(mp3Files) == 0):
        return []

    # If no parameters were specified, choose a random song
    if (songTitle == '' and performer == '' and album == ''):
        index = random.randint(0, len(mp3Files) - 1)
        return [mp3Files[index]]

    # Filter all songs that don't match designated title
    if (songTitle != ''):
        for entry in mp3Files:
            if (entry['title'].lower() != songTitle.lower()):
                mp3Files.remove(entry)

    # Filter all songs that don't match designated artist
    if (performer != ''):
        for entry in mp3Files:
            if (entry['artist'].lower() != performer.lower()):
                mp3Files.remove(entry)

    # Filter all songs that don't match designated album
    if (album != ''):
        for entry in mp3Files:
            if (entry['album'].lower() != album.lower()):
                mp3Files.remove(entry)

    # Remove all repeated files
    for entry in mp3Files:
        for entry2 in mp3Files:
            if (entry2 != entry and entry['title'] == entry2['title']
                    and entry['artist'] == entry2['artist']
                    and entry['album'] == entry2['album']):
                mp3Files.remove(entry2)

    return mp3Files
示例#13
0
def getTags(path):
    try:
        id3r = id3reader.Reader(path)
        
        song_info = {}
        song_info['Artist'] = id3r.getValue('performer')
        song_info['Album'] = id3r.getValue('album')
        song_info['Title'] = id3r.getValue('title')
        song_info['ReleaseDate'] = id3r.getValue('year')
        
        if song_info['Title']:
            music_data.append(song_info)
    except:
        print 'error',
示例#14
0
    def get_meta(self, fp):
        def decode_string(tag):
            for encoding in ['cp1251', 'utf-8', 'MacCyrillic']:
                try:
                    return tag.decode(encoding)
                except UnicodeDecodeError:
                    continue
            else:
                encoding = chardet.detect(tag)['encoding']
                try:
                    tag = tag.decode(encoding)
                except UnicodeDecodeError:
                    return None
                else:
                    return tag

        def decode_unicode(tag):
            try:
                tag = tag.encode('latin1')
            except UnicodeEncodeError:
                pass
            else:
                tag = decode_string(tag)
            return tag

        def convert(tag):
            if isinstance(tag, str):
                return decode_string(tag)
            elif isinstance(tag, unicode):
                return decode_unicode(tag)
            else:
                None

        try:
            id3r = id3reader.Reader(fp)
        except:
            log.info("Cannot read meta tag")
            return

        artist = convert(id3r.getValue('performer') or '')
        title = convert(id3r.getValue('title') or '')

        if artist and title:
            return {"artist": artist, "title": title}
        else:
            log.error("Bad meta tags '%s'-'%s'" % (artist, title))
            return None
示例#15
0
def searchForLovedSongs(searchForLovedSongs):
    path = raw_input("Enter the path to your music folder: ")
    if not os.path.exists(path):
        while True:
            path = raw_input(
                "The folder specified does not exist. Enter the path to your music folder: "
            )
            if not os.path.exists(path):
                break

    destination = raw_input(
        "Enter the path to destination folder (the loved songs will be copyied there): "
    )
    makePathOk(destination)

    filelist = parse_dirs(path)

    print "There were " + str(len(filelist)) + " files found"
    print "Please wait while the songs are verified (it might take a while)"

    for filename in filelist:
        if filename[-4:] == ".mp3":
            try:
                id3r = id3reader.Reader(filename)
            except UnicodeDecodeError:
                artist = "None"
                title = "None"
            except IOError:
                artist = "None"
                title = "None"
            else:
                artist = ensureutf8andstring(id3r.getValue('performer'))
                title = ensureutf8andstring(id3r.getValue('title'))

            if artist != "None" or title != "None":
                if lovedSongs[artist][title] == 1:
                    try:
                        shutil.copy(filename, destination)
                    except:
                        print '"' + artist + ' - ' + title + '" could not be copied'
                    else:
                        print '"' + artist + ' - ' + title + '" was successfully copied'

    print "parsing done"
示例#16
0
def getTags(path):
    try:
        id3r = id3reader.Reader(path)

        song_info = {}
        song_info['Title'] = id3r.getValue('title')
        song_info['Artist'] = id3r.getValue('performer')
        song_info['Album'] = id3r.getValue('album')
        year = id3r.getValue('year')
        y = re.match(r'(?<!\d)\d{4,7}(?!\d)', year)
        song_info['ReleaseYear'] = y.group(0)
        song_info['Genre'] = id3r.getValue('genre')
        song_info['Filename'] = path.split('/')[-1]
        song_info['Folder'] = path.split('/')[-2]

        if song_info['Title']:
            music_data.append(song_info)
    except:
        pass
示例#17
0
def generate(path):
    import id3reader
    import guidem.model

    if os.access(path, os.R_OK):
        print 'Access granted'
        for root, dirs, files in os.walk(path):
            root = os.path.join(os.getcwd(), root)
            for fname in files:
                file = open(os.path.join(root, fname), 'rb')
                contentlength = os.stat(os.path.join(root, fname)).st_size
                try:
                    id3r = id3reader.Reader(file)
                except:
                    continue
                artist = (id3r.getValue('performer') or '').decode('cp1251')
                title = (id3r.getValue('title') or '').decode('cp1251')
                composition = (id3r.getValue('album') or '').decode('cp1251')
                no = id3r.getValue('track') or None
                no = int(no.split('/')[0]) if no else None
                if artist and title:
                    file = guidem.model.File(
                        fname.decode('utf-8'),
                        os.path.join(root, fname).decode('utf-8'),
                        contentlength).db_add()
                    if file:
                        artist = guidem.model.Artist.get_or_add(artist)
                        if composition and no:
                            track = guidem.model.Track(title, artist, file.id, \
                                                       composition=composition, no=no).db_add()
                        else:
                            track = guidem.model.Track(title, artist,
                                                       file.id).db_add()
                        if track:
                            print 'Track %s - %s added.' % (artist, track)
                        else:
                            print 'Track not added.'
                    else:
                        print "Cannot add file: '%s'" % fname
        print 'Database generated'
    else:
        print 'Access denied'
示例#18
0
def getM3uString(fname):
    mp3file = open(fname, 'rb')

    caption, performer, title = '', '', ''
    try:
        mp3file.seek(0)
        id3 = id3reader.Reader(mp3file)
        performer = id3.getValue('performer')
        title = id3.getValue('title')
    except:
        safeprint("Couldn't read ID3 tag in file %s: %s" %
                  (fname, formatException()))

    if performer:
        caption += performer
    if title:
        if caption:
            caption += ' - '
        caption += title

    extinf = ''
    if caption:
        secs = 0
        try:
            mp3file.seek(0)
            secs = mp3secs(mp3file)
        except:
            safeprint("Couldn't read MP3 file %s: %s" %
                      (fname, formatException()))

        if isinstance(caption, type(u'')):
            caption = caption.encode('iso8859-1', 'replace')

        extinf = '#EXTINF:%d,%s\n' % (int(secs), caption)

    mp3file.close()

    fpath = fname.abspath()
    if isinstance(fpath, type(u'')):
        fpath = fpath.encode('iso8859-1', 'replace')

    return extinf + fpath + '\n'
示例#19
0
def getTrack():
    try:
        f = open(__PIPE)
        try:
            lines = f.read().strip().split('\n')
        finally:
            f.close()
    except IOError:
        # nothing to read
        pass
    else:
        k, v = lines[-1].split(':', 1)
        fileName = v.strip()
        # check, if "filename" is real file -- sometimes it can be URL!
        if os.path.isfile(fileName):
            id3 = id3reader.Reader(fileName)
            performer = id3.getValue('performer')
            title = id3.getValue('title')
            if not None in (performer, title):
                return (performer, title)
示例#20
0
def rename(src, is_numbering=False, n=None):
    try:
        logger.info("Path exists")
        id3r = id3reader.Reader(src)
        artist = id3r.getValue("performer")
        title = id3r.getValue("title")

        if artist is None or title is None:
            return None

        if is_numbering and n != None:
            filename = "%02d %s - %s" % (n, artist,
                                         title) + os.path.splitext(src)[1]
        else:
            filename = "%s - %s" % (artist, title) + os.path.splitext(src)[1]

        logger.info("New filename: " + filename)
        return sanitize(filename) if artist and title else src

    except:
        return None
示例#21
0
def main():
    parser = argparse.ArgumentParser(
            description='Sorts music into Artist/Album/01 - Song Title.mp3 like structures')
    parser.add_argument('-s', '--source', dest='source_dir', required=True,
            help='Source directory (with the unsorted music in it)')
    parser.add_argument('-d', '--destination',
            dest='destination_dir', required=True,
            help='Destination directory (where the sorted music goes)')
    args = parser.parse_args()
    for directory in os.walk(args.source_dir):
        for _file in directory[2]:
            _file = join(directory[0], _file)
            try:
                reader = id3reader.Reader(_file)
            except IOError:
                continue
            if not reader.getValue('performer'):
                print 'ERROR: skipping %s' % _file
                continue
            artist_album = os.path.join(args.destination_dir,
                    reader.getValue('performer'),
                    reader.getValue('album'))
            track = reader.getValue('track')
            if '/' in track:
                track = track.split('/')[0]
            if len(track) == 1:
                track = '0%s' % track
            new_file_name = '%s - %s.mp3' % (
                track, reader.getValue('title').replace('/', ','))
            new_file_path = join(artist_album, new_file_name)
            if exists(new_file_path):
                continue
            try:
                os.makedirs(artist_album)
            except OSError:
                pass
            shutil.copy2(_file, new_file_path)
            print 'Made: %s' % os.path.join(artist_album, new_file_name)
示例#22
0
def handleMP3(fpath, fname):
    """
    This function is called every time we identify a new MP3 file. It handles reading the ID3 tag and then adding the file to the appropriate playlists.
    """
    global playlist_ALL
    global playlist_dir
    global MP3_ROOT
    global PLAYLIST_ROOT

    # TODO: This is a hack because MPlayer doesn't give us what we need.
    # Read the rest of the information from the file directly, since MPlayer isn't telling us

    absolutePath = MP3_ROOT + fpath  # this is the actual (absolute path)

    try:
        id3r = id3reader.Reader(os.path.join(absolutePath, fname))
        #print "reading ID3 from "+os.path.join(absolutePath, fname) # DEBUG
        # Ask the reader for ID3 values:
        title = id3r.getValue('title')
        artist = id3r.getValue('performer')
        album = id3r.getValue('album')
        genre = id3r.getValue('genre')
        #displayName = artist+" - "+title+" ("+album+")"
        displayName = ""
        if artist != None:
            displayName = displayName + artist + " - "
        if title != None:
            displayName = displayName + title
        if album != None:
            displayName = displayName + " (" + album + ")"
    except id3reader.Id3Error, message:
        print "file " + absolutePath + "/" + fname + " Id3Error: ", message
        displayName = fname
        title = ""
        artist = ""
        album = ""
        genre = ""
示例#23
0
    def FromPath(self, path, attemptparse=True):
        """Rehydrate a track from its path."""

        new_track = False
        updated = False

        id_row = self.db.GetOneRow(
            'select track_id from paths where path = "%s";' % path)

        if id_row:
            id = id_row['track_id']
            self.persistant = self.db.GetOneRow(
                'select * from tracks where id=%d;' % id)
            if not self.persistant:
                raise Exception('No persistant data for track id: %s' % id)

            # There was a bug a while ago where we left underscores in the database.
            # Clean that up...
            for key in 'artist', 'album', 'song':
                if not key in self.persistant:
                    raise Exception(
                        'Required key %s missing for track path %s' %
                        (key, path))

                before = self.persistant[key]
                after = self.persistant[key].replace('_', ' ')
                if before != after:
                    self.persistant[key] = after
                    updated = True

        else:
            # This is a new track
            self.persistant = {}
            self.persistant['creation_time'] = datetime.datetime.now()
            new_track = True

        # Attempt to parse the path using Mikal's file naming scheme. 30 chars is
        # is the field length for ID3, and might indicate the tags have been
        # truncated
        if attemptparse:
            if (not 'artist' in self.persistant
                    or len(self.persistant.get('song', ' ')) == 30
                    or len(self.persistant.get('album', ' ')) == 30):
                m = _PATH_PARSE_RE.match(path)
                if m:
                    try:
                        self.persistant['artist'] = m.group(1).replace(
                            '_', ' ')
                        self.persistant['album'] = m.group(2).replace('_', ' ')
                        self.persistant['song'] = m.group(4).replace('_', ' ')
                        self.persistant['number'] = int(m.group(3)).replace(
                            '_', ' ')
                        updated = True

                    except:
                        pass

        # Use ID3 if we're missing information. This isn't as good as file parsing
        # as the ID3 fields have maximum lengths we sometimes hit.
        if not self.persistant.has_key('artist'):
            try:
                id3r = id3reader.Reader(path)
                if id3r.getValue('album'):
                    self.persistant['album'] = id3r.getValue('album')
                    updated = True
                if id3r.getValue('performer'):
                    self.persistant['artist'] = id3r.getValue('performer')
                    updated = True
                if id3r.getValue('title'):
                    self.persistant['song'] = id3r.getValue('title')
                    updated = True
                if id3r.getValue('track'):
                    try:
                        self.persistant['number'] = int(id3r.getValue('track'))
                        updated = True
                    except:
                        pass
            except:
                pass

        # Perhaps we have this MP3 under another path
        if not self.persistant.has_key('artist'):
            try:
                self.FromMeta(self.persistant['artist'],
                              self.persistant['album'],
                              self.persistant['number'],
                              self.persistant['song'])
                updated = True
            except:
                pass

        if new_track:
            # Now write this to the database to get an ID
            self.db.ExecuteSql(
                'insert into tracks(artist, album, song, number) '
                'values(%s, %s, %s, %d);' %
                (sql.FormatSqlValue('artist', self.persistant['artist']),
                 sql.FormatSqlValue('album', self.persistant['album']),
                 sql.FormatSqlValue('song', self.persistant['song']),
                 self.persistant.get('number', 0)))
            id = self.db.GetOneRow(
                'select last_insert_id();')['last_insert_id()']
            self.persistant['id'] = id

        if updated:
            print 'Updated track %s' % self.persistant['id']
            self.Store()
示例#24
0
文件: fileUpload.py 项目: sgelhaus/RT
    msvcrt.setmode(1, os.O_BINARY)  # stdout = 1
except ImportError:
    pass

form = cgi.FieldStorage()

# holds the file
fileitem = form['file']

if fileitem.filename:
    fn = os.path.basename(fileitem.filename)
    open('./audio/' + fn, 'wb').write(fileitem.file.read())

    db = MySQLdb.connect(host="localhost", user="******", passwd="3308", db="RT")
    cur = db.cursor()
    id3 = id3reader.Reader('./audio/' + fn)
    cur.execute(
        "INSERT INTO tracks (Title, Artist, Album, FileName) VALUES ('" +
        id3.getValue('title') + "','" + id3.getValue('performer') + "','" +
        id3.getValue('album') + "','" + fn + "');")
    db.close()

    message = 'The file was uploaded successfully.'

else:
    message = 'No file was uploaded'

print """\
Content-Type: text/html\n
<html>
<head>
示例#25
0
 files.sort()
 # recurse into subdirs
 for dir in dirs:
     results = process_dir(dir, results=results, coverFiles=coverFiles)
 # continue processing this dir once subdirs have been processed
 log.debug("evaluating " + thisDir)
 # if any of the given cover files exist, no further work required
 for coverFile in coverFiles:
     if coverFile in files:
         log.debug("cover file %s exists - skipping" % coverFile)
         return results
 for file in files:
     fileFullPath = os.path.join(thisDir, file)
     # check file for id3 tag info
     try:
         id3r = id3reader.Reader(fileFullPath)
     except Exception, err:
         log.error('exception: ' + str(err))
         continue
     # get values and sanitise nulls
     artist = id3r.getValue('performer')
     album = id3r.getValue('album')
     if artist == None: artist = ''
     if album == None: album = ''
     # if either artist or album found, append to results and return
     if artist or album:
         log.info("album details found: %s/%s in %s" % (artist, album, file))
         results.append((thisDir, artist, album))
         return results
 # no artist or album info found, return results unchanged
 return results
示例#26
0
def get_track(music_file):
    id3r = id3reader.Reader(music_file)
    track = int(id3r.getValue('track'))
    return track
示例#27
0
    def realread(self):
        fileread = self.fileread
        #print str(self) + str(oop)+str(fileread)
        print fileread
        if str(fileread).endswith(".mp3"):
            cmd = [
                os.environ.get('SUGAR_BUNDLE_PATH') + "/bin/mpg123",
                str(fileread)
            ]
        else:
            cmd = [
                os.environ.get('SUGAR_BUNDLE_PATH') + "/bin/mpg123", "-@",
                str(fileread)
            ]
        #print "playing "+ str(fileread)
        self._is_jornal = "yes"
        self._playingjnl = str(fileread)
        subprocess.Popen(cmd)

        if str(fileread).endswith(".pls"):
            id3, err = subprocess.Popen([
                "/bin/sh", "-c",
                "cat " + str(fileread) + " | grep Title1= | cut -d '=' -f2"
            ],
                                        stdout=subprocess.PIPE).communicate()
        elif str(fileread).endswith(".mp3"):
            id3r = id3reader.Reader(str(fileread))
            id3 = "Title: " + str(id3r.getValue('title')) + "\nArtist: " + str(
                id3r.getValue('performer')) + "\nAlbum: " + str(
                    id3r.getValue('album')) + ""
            #print id3
            #id3=id3.capitalize()
        else:
            id3tmp, err = subprocess.Popen(
                ["/bin/sh", "-c", "cat " + str(fileread)],
                stdout=subprocess.PIPE).communicate()
            id3 = "M3U stream at " + id3tmp + ""
        #print "id3 is "+str(id3)

        if id3 == "":
            id3 = "Unknown"

        self.play_button.connect('clicked', self._stop)
        self.play_button.set_icon_widget(self.pause_image)
        self.play_button.set_tooltip(_('Stop'))
        self.box_playing.remove(self.label_playing_url)
        self.label_playing_url = gtk.Label(str(id3))
        self.label_playing_url.set_justify(gtk.JUSTIFY_CENTER)
        self.label_playing_url.set_line_wrap(True)
        self.label_playing_url.modify_font(pango.FontDescription("Sans 14"))
        self.box_playing.add(self.label_playing_url)
        self.label_title.set_text(_("Now Playing"))
        if fileread.endswith('.mp3'):
            id3title = str(id3r.getValue('performer')) + " - " + str(
                id3r.getValue('title'))
        else:
            id3title = id3
        print id3title
        print fileread
        # not quite working... doesnt update after 1st song!
        #self.set_title("Now Playing:\n"+str(id3title))	=
        self.show_all()
示例#28
0
def parseFilename(filename):
    #check out id3 for recently downloaded files
    origfilename = filename
    id3r = id3reader.Reader(sourceDir + filename)
    filename = id3r.getValue('title')
    log_info("Filename:: " + origfilename + "; Parsed to:: " + filename)
    def MyID3(self, fileLoc):

        # Create a scrollable container
        self.scroll = ScrollView(do_scroll_x=(False))

        # Asign the directory to a variable
        self.musicDirectory = fileLoc

        # Create a grid background to allign the buttons
        self.gridLayer = GridLayout(cols=1, size_hint=(1, None))

        # Size fix for grid
        self.gridLayer.bind(minimum_height=self.gridLayer.setter('height'),
                            minimum_width=self.gridLayer.setter('width'))

        # Add the grid widget to the scroller
        self.scroll.add_widget(self.gridLayer)

        # Artist label
        self.artist = Label()

        # Song label
        self.song = Label()

        # Album label
        self.album = Label()

        # Begin the alternating count to alternate the background images (see bellow)
        self.alternate = 1

        # Process each file in the targeted directory
        for file in os.listdir(self.musicDirectory):

            # Check if the file is an MP3
            if file.endswith(".mp3"):

                # Run ID3 Reader to gather the ID3 data
                id3r = id3reader.Reader(self.musicDirectory + file)

                # Try to gather the artist ID3 data
                try:
                    self.artist.text = self.stripSquare(
                        id3r.getValue('performer'))
                except:
                    self.artist.text = "Not Found"

                # Try to gather the song title ID3 data
                try:
                    self.song.text = self.stripSquare(id3r.getValue('title'))

                except:
                    self.song.text = "Not Found"

                # Try to gather the album ID3 data
                try:
                    self.album.text = self.stripSquare(id3r.getValue('album'))
                except:
                    self.album.text = "Not Found"

                # Create a spawn of the music button class
                self.temp = MusicButton(text="testing",
                                        halign="center",
                                        size_hint=(1, None),
                                        height=("80dp"),
                                        background_normal='images/listone.png',
                                        background_down='images/bk.png',
                                        markup=True)

                # Set the music buttons filename attribute
                self.temp.musicFileName = file

                # Alternate the background colours
                if self.alternate % 2 == 0:
                    self.temp.background_normal = 'images/listtwo.png'
                self.alternate += 1

                # Shorten the Ssong title to prevent overflow.
                self.song.text = self.song.text[:30] + (self.song.text[30:]
                                                        and '..')

                # Format the music button text
                self.temp.text = "[anchor=title1][size=18sp][color=#4D5158]" + self.song.text + "[/color][/size]\n[color=#AAAAAA]" + self.artist.text + "[/color]"
                self.gridLayer.add_widget(self.temp)

                # Link the button press and release to events
                self.temp.bind(on_press=self.songSelect,
                               on_release=self.songRelease)

        # Return the newly created window
        return self.scroll
示例#30
0
import id3reader
import os
import shutil
filename=""
flag=0
src ='E:\musiq'
#C:\Users\TMZ\Music
songs = []
with open("database.txt","w") as c:
   for root, dirs, files in os.walk(src):
      for f in files:
         list =[]
         filename = os.path.join(root, f)
         if filename.endswith('.mp3'):
            #print filename
            id3r = id3reader.Reader(filename)
            try:
               if str(id3r.getValue('title'))!= "None" and str(id3r.getValue('performer'))!="None" and str(id3r.getValue('album'))!="None" and str(id3r.getValue('year'))!="None" and str(id3r.getValue('genre')) !="None":
                  list.append(str(id3r.getValue('title')))
                  list.append(str(id3r.getValue('performer')))
                  list.append(str(id3r.getValue('album')))
                  list.append(str(id3r.getValue('year')))
                  list.append(str(id3r.getValue('genre')))
                  dest = "E:\songs\\" + f
                  shutil.copy(filename,dest)
            except:
               print filename
            else:
               #print list
               if list not in songs:
                  songs.append(list)