Returns the lyrics found in musixmatch for the specified mp3 file or an
    empty string if not found.
559572
def musixmatch(song):
    
    escape = re.sub("'-¡¿", '', URLESCAPE)
    translate = {
        escape: '',
        ' ': '-'
    }
    artist = song.artist.title()
    artist = re.sub(r"( '|' )", '', artist)
    artist = re.sub(r"'", '-', artist)
    title = song.title
    title = re.sub(r"( '|' )", '', title)
    title = re.sub(r"'", '-', title)

    artist = normalize(artist, translate)
    artist = re.sub(r'\-{2,}', '-', artist)
    title = normalize(title, translate)
    title = re.sub(r'\-{2,}', '-', title)

    url = 'https://www.musixmatch.com/lyrics/{}/{}'.format(artist, title)
    soup = get_url(url)
    text = ''
    contents = soup.find_all('p', class_='mxm-lyrics__content')
    for p in contents:
        text += p.get_text().strip()
        if p != contents[-1]:
            text += '\n\n'

    return text.strip()
1156118
def instantiateSong(fileName):
    """"""
    ext = detectFormat(fileName)
    if(ext == "mp3"):
        return pd.AudioSegment.from_mp3(fileName)
    elif(ext == "wav"):
        return pd.AudioSegment.from_wav(fileName)
    elif(ext == "ogg"):
        return pd.AudioSegment.from_ogg(fileName)
    elif(ext == "flv"):
        return pd.AudioSegment.from_flv(fileName)
    elif(ext == "m4a"):
        return pd.AudioSegment.from_file(fileName, "mp4")
    else:
        return pd.AudioSegment.from_file(fileName, ext)
1341692
def get_song_urls(song_input):
    
    YOUTUBECLASS = 'spf-prefetch'

    html = requests.get("https://www.youtube.com/results",
                        params={'search_query': song_input})
    soup = BeautifulSoup(html.text, 'html.parser')

    soup_section = soup.findAll('a', {'rel': YOUTUBECLASS})

    # Use generator over list, since storage isn't important
    song_urls = ('https://www.youtube.com' + i.get('href')
                 for i in soup_section)
    song_titles = (i.get('title') for i in soup_section)

    youtube_list = list(zip(song_urls, song_titles))

    del song_urls
    del song_titles

    return youtube_list
29999
public function find($string)
    {
        try {
            $array = [];

            $totalLength = null;

            $totalFileSize = null;

            if ($string != null) {
                $searchFile = $this->getSearchFile();

                clearstatcache();

                if (is_file($searchFile)) {
                    /**
                     * Error: Search File is Empty
                     */
                    if (filesize($searchFile) <= '0') {
                        $errorString = 'The search file is currently empty. ';
                        $errorString .= 'Use the Import Tool to populate the Search Results';

                        $translateError = $this->translate->translate(
                            $errorString,
                            'mp3'
                        );

                        $location = $this->serverUrl
                            ->get('url')
                            ->__invoke(
                                'mp3-search',
                                [
                                    'flash' => $translateError
                                ]
                            );

                        header('Location: ' . $location);

                        exit;
                    }

                    $handle = fopen(
                        $searchFile,
                        'r'
                    );

                    $contents = fread(
                        $handle,
                        filesize($searchFile)
                    );

                    $unserialize = preg_grep(
                        '/' . $string . '/i',
                        unserialize($contents)
                    );

                    fclose($handle);

                    if (count($unserialize) > '0') {
                        foreach ($unserialize as $path) {
                            $this->memoryUsage();

                            /**
                             * Set Paths
                             */
                            $basePath = $path;

                            $fullPath = $this->getSearchPath() . '/' . $path;

                            clearstatcache();

                            if (is_dir($fullPath)) {
                                $array[] = [
                                    'name'     => $path,
                                    'basePath' => $basePath,
                                    'base64'   => base64_encode(
                                        ltrim(
                                            $basePath,
                                            '/'
                                        )
                                    ),
                                    'fullPath' => $fullPath,
                                    'type'     => 'dir'
                                ];
                            }

                            if (is_file($fullPath)) {
                                $id3 = $this->getId3($fullPath);

                                $title = !empty($id3['comments_html']['title'])
                                    ? implode(
                                        '<br>',
                                        $id3['comments_html']['title']
                                    )
                                    : basename($fullPath);

                                $bitRate = !empty($id3['audio']['bitrate'])
                                    ? round($id3['audio']['bitrate'] / '1000')
                                    : '-';

                                $length = !empty($id3['playtime_string'])
                                    ? $id3['playtime_string']
                                    : '-';

                                $fileSize = !empty($id3['filesize'])
                                    ? $id3['filesize']
                                    : '-';

                                $totalLength += $this->convertTime($length);

                                $totalFileSize += $fileSize;

                                $array[] = [
                                    'name'     => $path,
                                    'basePath' => $basePath,
                                    'base64'   => base64_encode(
                                        ltrim(
                                            $basePath,
                                            '/'
                                        )
                                    ),
                                    'fullPath' => $fullPath,
                                    'type'     => 'file',
                                    'id3'      => [
                                        'title'    => $title,
                                        'bitRate'  => $bitRate,
                                        'length'   => $length,
                                        'fileSize' => $fileSize
                                    ]
                                ];
                            }
                        }
                    }
                } else {
                    throw new \Exception(
                        $searchFile . ' ' . $this->translate->translate(
                            'was not found',
                            'mp3'
                        )
                    );
                }
            }

            $paginator = new Paginator(new ArrayAdapter($array));

            $paginator->setDefaultItemCountPerPage(
                (count($array) > '0')
                    ? count($array)
                    : '1'
            );

            if ($totalLength > '0') {
                $totalLength = sprintf(
                    "%d:%02d",
                    ($totalLength / '60'),
                    $totalLength % '60'
                );
            }

            return [
                'paginator'     => $paginator,
                'totalLength'   => $totalLength,
                'totalFileSize' => $totalFileSize,
                'search'        => (is_file($this->getSearchFile()))
            ];
        } catch (\Exception $e) {
            throw $e;
        }
    }
114928
def convert(self):
        """"""
        if self.downloaded is False:
            raise serror("Track not downloaded, can't convert file..")
        filetype = magic.from_file(self.filepath, mime=True)
        if filetype == "audio/mpeg":
            print("File is already in mp3 format. Skipping convert.")
            return False

        rootpath = os.path.dirname(os.path.dirname(self.filepath))
        backupdir = rootpath + "/backups/" + self.get("username")
        if not os.path.exists(backupdir):
            os.makedirs(backupdir)

        backupfile = "%s/%s%s" % (
            backupdir,
            self.gen_filename(),
            self.get_file_extension(self.filepath))
        newfile = "%s.mp3" % self.filename_without_extension()

        os.rename(self.filepath, backupfile)
        self.filepath = newfile

        print("Converting to %s.." % newfile)
        song = AudioSegment.from_file(backupfile)
        return song.export(newfile, format="mp3")
285249
def findGap(song):
    """"""
    try:
        silence = pd.silence.detect_silence(song)
    except IOError:
        print("There isn't a song there!")

    maxlength = 0

    for pair in silence:
        length = pair[1] - pair[0]
        if length >= maxlength:
            maxlength = length
            gap = pair

    return gap
27709
def readAudioFile(path):
    '''
    
    '''
    extension = os.path.splitext(path)[1]

    try:
        #if extension.lower() == '.wav':
            #[Fs, x] = wavfile.read(path)
        if extension.lower() == '.aif' or extension.lower() == '.aiff':
            s = aifc.open(path, 'r')
            nframes = s.getnframes()
            strsig = s.readframes(nframes)
            x = numpy.fromstring(strsig, numpy.short).byteswap()
            Fs = s.getframerate()
        elif extension.lower() == '.mp3' or extension.lower() == '.wav' or extension.lower() == '.au' or extension.lower() == '.ogg':            
            try:
                audiofile = AudioSegment.from_file(path)
            #except pydub.exceptions.CouldntDecodeError:
            except:
                print("Error: file not found or other I/O error. "
                      "(DECODING FAILED)")
                return (-1,-1)                

            if audiofile.sample_width==2:                
                data = numpy.fromstring(audiofile._data, numpy.int16)
            elif audiofile.sample_width==4:
                data = numpy.fromstring(audiofile._data, numpy.int32)
            else:
                return (-1, -1)
            Fs = audiofile.frame_rate
            x = []
            for chn in list(range(audiofile.channels)):
                x.append(data[chn::audiofile.channels])
            x = numpy.array(x).T
        else:
            print("Error in readAudioFile(): Unknown file type!")
            return (-1,-1)
    except IOError: 
        print("Error: file not found or other I/O error.")
        return (-1,-1)

    if x.ndim==2:
        if x.shape[1]==1:
            x = x.flatten()

    return (Fs, x)
49703
def load_from_file(filename):
    
    if os.path.isdir(filename):
        logger.error("Err: File '%s' is a directory", filename)
        return None
    if not os.path.isfile(filename):
        logger.error("Err: File '%s' does not exist", filename)
        return None

    try:
        with open(filename, 'r') as sourcefile:
            songs = [line.strip() for line in sourcefile]
    except IOError as error:
        logger.exception(error)
        return None
    songs = set(Song.from_filename(song) for song in songs)
    return songs.difference({None})
1281808
def find_matches(text):
    
    """
    path = os.path.expanduser(text)
    if os.path.isdir(path) and not path.endswith('/'):
        return [ text + '/' ]

    pattern = path + '*'
    is_implicit_cwd = not (path.startswith('/') or path.startswith('./'))
    if is_implicit_cwd:
        pattern = './' + pattern
    rawlist = glob.glob(pattern)
    ret = []
    for fname in rawlist:
        if is_implicit_cwd:
            fname = fname[2:]
        if os.path.isdir(fname):
            ret.append(fname + '/')
        else:
            ret.append(fname)
    return ret
74719
def match_string(self, string, word=0, offset=0):
        
        if word:
            return self.get_string(offset) == string
        return self.get_length(len(string), offset) == string
873155
def save_tag_to_audio_file(audio_file, tracklisting):
    
    print("Trying to tag {}".format(audio_file))
    f = mediafile.MediaFile(audio_file)

    if not f.lyrics:
        print("No tracklisting present. Creating lyrics tag.")
        f.lyrics = 'Tracklisting' + '\n' + tracklisting
    elif tracklisting not in f.lyrics:
        print("Appending tracklisting to existing lyrics tag.")
        f.lyrics = f.lyrics + '\n\n' + 'Tracklisting' + '\n' + tracklisting
    else:
        print("Tracklisting already present. Not modifying file.")
        raise TagNotNeededError

    f.save()
    print("Saved tag to file:", audio_file)
138895
def find_matches(self, content, file_to_handle):
        
        # look for all match groups in the content
        groups = [match.groupdict() for match in
                  self.match_expression.finditer(content)]
        # filter out content not in the matchgroup
        matches = [group['matchgroup'] for group in groups
                   if group.get('matchgroup')]

        logger.info('Found %s matches in %s', len(matches), file_to_handle)
        # We only need the unique strings found as we'll be replacing each
        # of them. No need to replace the ones already replaced.
        return list(set(matches))
71902
function toMusicXML() {
        $out = '';

        $out .= '<time';
        if (isset($this->symbol)) {
            $out .= ' symbol="'.$this->symbol.'"';
        }

        $out .= '>';
        if (isset($this->beats)) {
            $out .= '<beats>'.$this->beats.'</beats>';
        }

        if (isset($this->beatType)) {
            $out .= '<beat-type>'.$this->beatType.'</beat-type>';
        }

        $out .= '</time>';

        return $out;
    }
251816
def parse_midi_file(self, file):
        
        try:
            f = open(file, 'r')
        except:
            raise IOError('File not found')
        self.bytes_read = 0
        header = self.parse_midi_file_header(f)
        tracks = header[1]
        result = []
        while tracks > 0:
            events = self.parse_track(f)
            result.append(events)
            tracks -= 1
        f.close()
        return (header, result)
974716
def mp3(self, sha, **kwargs):
        """"""
        return self._queue_msg({'cmd': cmd.CMD_MESSAGE_MP3,
                                'sha': _get_bytes(sha)}, **kwargs)
237955
function getFile (str) {
  var ret = null
  var match = /[0-9]+,[0-9]+,.*/.test(str)
  if (!match) {
    return null
  }
  var a = str.split(',')
  if (a && a[2]) {
    ret = a[2]
    return ret
  } else {
    return null
  }
  if (isNaN(ret)) {
    return null
  }
  return ret
}
564168
def save_lyrics(self, filename=None, extension='json', verbose=True,
                    overwrite=None, binary_encoding=False):
        """"""
        extension = extension.lstrip(".")
        assert (extension == 'json') or (extension == 'txt'), "format_ must be JSON or TXT"

        # Determine the filename
        if filename:
            for ext in ["txt", "TXT", "json", "JSON"]:
                filename = filename.replace("." + ext, "")
            filename += "." + extension
        else:
            filename = "Lyrics_{}_{}.{}".format(self.artist.replace(" ", ""),
                                                self.title.replace(" ", ""),
                                                extension).lower()
            filename = self._sanitize_filename(filename)

        # Check if file already exists
        write_file = False
        if not os.path.isfile(filename):
            write_file = True
        elif overwrite:
            write_file = True
        else:
            if input("{} already exists. Overwrite?\n(y/n): ".format(filename)).lower() == 'y':
                write_file = True

        # Format lyrics as either .txt or .json
        if extension == 'json':
            lyrics_to_write = {'songs': [], 'artist': self.artist}
            lyrics_to_write['songs'].append(self.to_dict())
        else:
            lyrics_to_write = self.lyrics

        if binary_encoding:
            lyrics_to_write = lyrics_to_write.encode('utf8')

        # Write the lyrics to either a .json or .txt file
        if write_file:
            with open(filename, 'wb' if binary_encoding else 'w') as lyrics_file:
                if extension == 'json':
                    json.dump(lyrics_to_write, lyrics_file)
                else:
                    lyrics_file.write(lyrics_to_write)
            if verbose:
                print('Wrote {} to {}.'.format(self.title, filename))
        else:
            if verbose:
                print('Skipping file save.\n')
        return lyrics_to_write