Scrapes a Mixcloud page for a track's important information.

    Returns:
        dict: containing audio data
428354
def get_audiomack_data(url):
    

    data = {}
    request = requests.get(url)

    mp3_url = request.text.split('class="player-icon download-song" title="Download" href="')[1].split('"')[0]
    artist = request.text.split('<span class="artist">')[1].split('</span>')[0].strip()
    title = request.text.split('<span class="artist">')[1].split('</span>')[1].split('</h1>')[0].strip()
    artwork_url = request.text.split('<a class="lightbox-trigger" href="')[1].split('" data')[0].strip()

    data['mp3_url'] = mp3_url
    data['title'] = title
    data['artist'] = artist
    data['artwork_url'] = artwork_url
    data['year'] = None

    return data
1320193
def _track_from_response(result, timeout):
    
    response = result['response']
    status = response['track']['status'].lower()

    if status == 'pending':
        # Need to wait for async upload or analyze call to finish.
        result = _wait_for_pending_track(response['track']['id'], timeout)
        response = result['response']
        status = response['track']['status'].lower()

    if not status == 'complete':
        track_id = response['track']['id']
        if status == 'pending':
            raise Exception('%s: the operation didn\'t complete before the timeout (%d secs)' %
                            (track_id, timeout))
        else:
            raise Exception('%s: there was an error analyzing the track, status: %s' % (track_id, status))
    else:
        # track_properties starts as the response dictionary.
        track_properties = response['track']
        # 'id' and 'md5' are separated to construct the Track object.
        identifier = track_properties.pop('id')
        md5        = track_properties.pop('md5', None) # tracks from song api calls will not have an md5
        # Pop off the audio_summary dict and make those keys attributes
        # of the Track. This includes things like tempo, energy, and loudness.
        track_properties.update(track_properties.pop('audio_summary'))
        return Track(identifier, md5, track_properties)
389280
def parse_track(self, fp):
        
        events = []
        chunk_size = self.parse_track_header(fp)
        bytes = chunk_size
        while chunk_size > 0:
            (delta_time, chunk_delta) = self.parse_varbyte_as_int(fp)
            chunk_size -= chunk_delta
            (event, chunk_delta) = self.parse_midi_event(fp)
            chunk_size -= chunk_delta
            events.append([delta_time, event])
        if chunk_size < 0:
            print 'yikes.', self.bytes_read, chunk_size
        return events
22810
def get_lastfm():
    

    filename = os.path.join(_download.LOCAL_CACHE_DIR, "lastfm_360k.hdf5")
    if not os.path.isfile(filename):
        log.info("Downloading dataset to '%s'", filename)
        _download.download_file(URL, filename)
    else:
        log.info("Using cached dataset at '%s'", filename)

    with h5py.File(filename, 'r') as f:
        m = f.get('artist_user_plays')
        plays = csr_matrix((m.get('data'), m.get('indices'), m.get('indptr')))
        return np.array(f['artist']), np.array(f['user']), plays
306901
def process_audiomack(vargs):
    

    artist_url = vargs['artist_url']

    if 'audiomack.com' in artist_url:
        mc_url = artist_url
    else:
        mc_url = 'https://audiomack.com/' + artist_url

    filenames = scrape_audiomack_url(mc_url, num_tracks=vargs['num_tracks'], folders=vargs['folders'], custom_path=vargs['path'])

    if vargs['open']:
        open_files(filenames)

    return
45579
def resolve(track_url):
    
    try:
        path = urlparse.urlparse(track_url).path
        tracks = client.get('/tracks', q=path)

        if tracks:
            return tracks[0]
        else:
            raise ValueError('Track not found for URL {}'.format(track_url))
    except Exception as e:
        raise ValueError('Error obtaining track by url: {}'.format(str(e)))
440058
def get_metadata(file_name, client_id, client_secret):
    

    song_name = improve_name(file_name)  # Remove useless words from title
    client_credentials_manager = SpotifyClientCredentials(client_id, client_secret)

    spotify = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
    results = spotify.search(song_name, limit=1)

    results = results['tracks']['items'][0]  # Find top result
    album = results['album']['name']  # Parse json dictionary
    artist = results['album']['artists'][0]['name']
    song_title = results['name']
    album_art = results['album']['images'][0]['url']

    return artist, album, song_title, album_art
1038624
def find_closest_match(target_track, tracks):
    
    track = None
    # Get a list of (track, artist match ratio, name match ratio)
    tracks_with_match_ratio = [(
        track,
        get_similarity(target_track.artist, track.artist),
        get_similarity(target_track.name, track.name),
    ) for track in tracks]
    # Sort by artist then by title
    sorted_tracks = sorted(
        tracks_with_match_ratio,
        key=lambda t: (t[1], t[2]),
        reverse=True  # Descending, highest match ratio first
    )
    if sorted_tracks:
        track = sorted_tracks[0][0]  # Closest match to query
    return track
599393
def _get_selectable(self):
        '''
        
        '''
        # Save some typing
        cursong = self.loop[self.song][0]
        
        if self.dif_song and len(cursong) > 1:
            # Position is relative to the intro of the track,
            # so we we will get the both the intro and body.
            s = cursong[0] + cursong[1]
        else:
            # Position is relative to the body of the track, so just get that.
            s = cursong[-1]
        # Return what we found
        return s
713566
function(track) {
  var request = new XMLHttpRequest()
  request.open('GET', 'sounds/' + track + '.wav', true)
  request.responseType = 'arraybuffer'
  request.onload = function() {
    context.decodeAudioData(request.response, function(buffer) {
      var createNode = function() {
        var node = context.createBufferSource()
        node.buffer = buffer
        node.connect(context.destination)
        return node
      }
      soundBank[track] = { createNode: createNode }
    })
  }
  request.send()
}
940347
def scrape_bandcamp_url(url, num_tracks=sys.maxsize, folders=False, custom_path=''):
    

    filenames = []
    album_data = get_bandcamp_metadata(url)

    # If it's a list, we're dealing with a list of Album URLs,
    # so we call the scrape_bandcamp_url() method for each one
    if type(album_data) is list:
        for album_url in album_data:
            filenames.append(scrape_bandcamp_url(album_url, num_tracks, folders, custom_path))
        return filenames

    artist = album_data["artist"]
    album_name = album_data["album_name"]

    if folders:
        if album_name:
            directory = artist + " - " + album_name
        else:
            directory = artist
        directory = sanitize_filename(directory)
        directory = join(custom_path, directory)
        if not exists(directory):
            mkdir(directory)

    for i, track in enumerate(album_data["trackinfo"]):

        if i > num_tracks - 1:
            continue

        try:
            track_name = track["title"]
            if track["track_num"]:
                track_number = str(track["track_num"]).zfill(2)
            else:
                track_number = None
            if track_number and folders:
                track_filename = '%s - %s.mp3' % (track_number, track_name)
            else:
                track_filename = '%s.mp3' % (track_name)
            track_filename = sanitize_filename(track_filename)

            if folders:
                path = join(directory, track_filename)
            else:
                path = join(custom_path, sanitize_filename(artist) + ' - ' + track_filename)

            if exists(path):
                puts_safe(colored.yellow("Track already downloaded: ") + colored.white(track_name))
                continue

            if not track['file']:
                puts_safe(colored.yellow("Track unavailble for scraping: ") + colored.white(track_name))
                continue

            puts_safe(colored.green("Downloading") + colored.white(": " + track_name))
            path = download_file(track['file']['mp3-128'], path)

            album_year = album_data['album_release_date']
            if album_year:
                album_year = datetime.strptime(album_year, "%d %b %Y %H:%M:%S GMT").year

            tag_file(path,
                     artist,
                     track_name,
                     album=album_name,
                     year=album_year,
                     genre=album_data['genre'],
                     artwork_url=album_data['artFullsizeUrl'],
                     track_number=track_number,
                     url=album_data['url'])

            filenames.append(path)

        except Exception as e:
            puts_safe(colored.red("Problem downloading ") + colored.white(track_name))
            print(e)
    return filenames
180738
def spotify(self):
        
        (text, color) = self._get_text()
        response = {
            "cached_until": self.py3.time_in(self.cache_timeout),
            "color": color,
            "full_text": text,
        }
        return response
627845
def trackSeek(path, artist, album, track, trackNum, fmt):
    """"""
    hiddenName = "(Hidden Track).{}".format(fmt)
    trackName = track + ".{}".format(fmt)
    songIn = instantiateSong(path)
    times = findGap(songIn)
    saveFiles(trackName, hiddenName, splitSong(songIn, times[0], times[1]), artist, album, trackNum)
    # return [path, track.rsplit('/',1)[0] +'/{}'.format(hiddenName)]
    return [trackName, hiddenName]
232877
def get_hard_track_url(item_id):
    

    streams_url = "https://api.soundcloud.com/i1/tracks/%s/streams/?client_id=%s&app_version=%s" % (
    item_id, AGGRESSIVE_CLIENT_ID, APP_VERSION)
    response = requests.get(streams_url)
    json_response = response.json()

    if response.status_code == 200:
        hard_track_url = json_response['http_mp3_128_url']
        return hard_track_url
    else:
        return None
505877
def get_genres(self, *args, **kwargs):
        
        args = tuple(['genres'] + list(args))
        return self.get_music_library_information(*args, **kwargs)
604440
async def recv(self):
        
        if self.readyState != 'live':
            raise MediaStreamError

        sample_rate = 8000
        samples = int(AUDIO_PTIME * sample_rate)

        if hasattr(self, '_timestamp'):
            self._timestamp += samples
            wait = self._start + (self._timestamp / sample_rate) - time.time()
            await asyncio.sleep(wait)
        else:
            self._start = time.time()
            self._timestamp = 0

        frame = AudioFrame(format='s16', layout='mono', samples=samples)
        for p in frame.planes:
            p.update(bytes(p.buffer_size))
        frame.pts = self._timestamp
        frame.sample_rate = sample_rate
        frame.time_base = fractions.Fraction(1, sample_rate)
        return frame
1149601
def extract_listing(pid):
    """"""
    print("Extracting tracklisting...")
    listing_etree = open_listing_page(pid + '/segments.inc')
    track_divs = listing_etree.xpath('//div[@class="segment__track"]')

    listing = []
    for track_div in track_divs:
        try:
            artist_names = track_div.xpath('.//span[@property="byArtist"]'
                                           '//span[@class="artist"]/text()')
        except ValueError:
            artist_names = ['']

        if not artist_names:
            artist_names = ['']

        if len(artist_names) > 1:
            artists = ', '.join(artist_names[:-1]) + ' & ' + artist_names[-1]
        else:
            artists = artist_names[0]

        try:
            title, = track_div.xpath('.//p/span[@property="name"]/text()')
        except ValueError:
            title = ''

        try:
            label, = track_div.xpath('.//abbr[@title="Record Label"]'
                                     '/span[@property="name"]/text()')
        except ValueError:
            label = ''
        listing.append((artists, title, label))
    return listing