def find(songname): client = Client() client.init() songs = [] print "start search" for song in client.search(songname, Client.SONGS): songs.append(song) if songs: return songs[0]
def get_list_popular_music(request): perido = request.GET.get('period') client = Client() client.init() if perido == '1': popular_music = client.popular(period=Client.DAILY) else: popular_music = client.popular(period=Client.MONTHLY) musicas = [] for musica in popular_music: musicas.append(musica.export()) return HttpResponse(json.dumps(musicas), mimetype="application/json")
def search_grooveshark(query): """ Makes a search on Grooveshark and return the songs. """ logger.debug("Searching Grooveshark for: '%s'", query) client = Client() client.init() resolve_pool = ThreadPool(processes=16) track_list = resolve_pool.map(get_track, client.search(query)) resolve_pool.close() return [song for song in track_list if song]
def PlayMusic(self, userinput): client = Client() client.init() searchquery = userinput.split("song")[1] try: song = next(client.search(searchquery, type='Songs')) p = subprocess.Popen([ "exec cvlc " + song.stream.url + " vlc://quit --quiet > /dev/null" ], shell=True) return "Playing " + str(song) except StopIteration: return "It don't see that song."
class groove_controller: def __init__(self, manager): self.client = Client() self.client.init() self.manager = manager def checkSong(self, song): instance = vlc.libvlc_new(1, ["-q"]) try: media = instance.media_new(song.stream.url) return True except TypeError: print("Error found adding: " + '\033[92m' + song.name + '\033[0m' + " searching for playable version") return False def getSong(self, songName): songs = self.client.search(songName, type='Songs') try: song = songs.next() while True: if self.checkSong(song): print("Found: " + '\033[92m' + song.name + " - " + song.artist.name + '\033[0m') return song else: song = songs.next() except Exception as e: return "Error" def getAll(self, songName): art = self.client.search(songName, Client.ARTISTS) return art.next().songs def getManySongs(self, search ,n): foundSongs = self.client.search(search, type='Fast') returnData = [] songCount = 0 for song in foundSongs: returnData.append({'song': song['SongName'], 'artist': song['ArtistName'], 'album': song['AlbumName'], 'SongID': song['SongID'], 'ArtistID': song['ArtistID']}) songCount += 1 if songCount > 19: break return returnData
def play_a_song(uri): """ Play a song from Grooveshark. Needs to have a token. http://grooveshark.com/s/Because+Of+You/4DYDAi Token: 4DYDAi """ logger.debug("Playing Grooveshark Song '%s'", uri) # Get token from uri token = urlparse(uri).path.split('?')[0].split('/')[-1] client = Client() client.init() song = client.get_song_by_token(token) return get_track(song)
def download_musics(request): musicas = json.loads(request.GET.get('musicas', '[]')) if musicas: client = Client() client.init() musics_list = [] for musica in musicas: song = Song.from_export(musica, client.connection) musics_list.append(song) zip_path = download_music_temp_file(musics_list) response = HttpResponse(FileWrapper(file(zip_path)), content_type='application/zip', mimetype="application/zip") response['Content-Disposition'] = 'attachment; filename=myfile.zip' response['Content-Length'] = os.path.getsize(zip_path) return response else: raise Http404
def get_gsresults(searchterms): c = Client() c.init() d = c.search(searchterms) x = 0 v = 0 client = soundcloud.Client(client_id='dcc1e7da1893fe098685ba22946454eb') tracks = client.get('/tracks', q=searchterms, license='cc-by-sa') r = [] for i in tracks.data: if x < 10: r.append({'artist':i.user['username'], 'title':i.title, 'url':i.id, 'arturl':i.artwork_url}) x += 1 continue for i in d: if v < 10: r.append({'album':i._album_name, 'artist':i._artist_name, 'title':i.name, 'url':i.stream.url, 'arturl':i._cover_url}) v += 1 return r
def play_a_playlist(uri): """ Play a playlist from Grooveshark. http://grooveshark.com/playlist/Office+Hours+Jazz/19537110 Playlist ID: 19537110 """ logger.debug("Playing Grooveshark Playlist '%s'", uri) # Get playlist_id from uri playlist_id = urlparse(uri).path.split('?')[0].split('/')[-1] client = Client() client.init() playlist = client.playlist(playlist_id) resolve_pool = ThreadPool(processes=16) playlist = resolve_pool.map(get_track, playlist.songs) resolve_pool.close() return [song for song in playlist if song]
def search_for_musics(query, option): client = Client() client.init() musicas_list = [] if option == '1': musicas = client.search(query, Client.SONGS) for musica in musicas: musicas_list.append(musica.export()) elif option == '2': musicas = client.search(query, Client.ALBUMS) for musica in musicas: musicas_list.append(musica.export()) elif option == '3': musicas = client.search(query, Client.ARTISTS) for musica in musicas: musicas_list.append(musica.export()) elif option == '4': playlist = client.playlist(query) for musica in playlist: musicas_list.append(musica.export()) else: musicas_list = [] return musicas_list
class GroovesharkPlugin: __slots__ = ('client', 'songmap') def __init__(self): self.client = Client() self.client.init() self.songmap = {} def getSongRec(self, lst): lst = list(lst) if len(lst) == 0: print("Sorry Charlie. No Results.") return None i, _ = inputChoice(list(res.name + " by " + res.artist.name if type(res) == grooveshark.classes.Song else res.name for res in lst)) c = lst[i] if type(c) is grooveshark.classes.Song: return c return self.getSongRec(c.songs) def pickSong(self): responseTuple = inputChoice(["Song", "Artist", "Album"]) if responseTuple == None: return None else: typ,_ = responseTuple typ = [Client.SONGS, Client.ARTISTS, Client.ALBUMS][typ] search = input('Grooveshark search: ') song = self.getSongRec(self.client.search(search, typ)) if song == None: return None retval = Song(song.name, song.artist.name) self.songmap[retval] = song.safe_download() return retval def getSongData(self, song): return self.songmap[song]
class Grooveshark(Application): __URLS__ = {'/desktop/.*|/icons/.*' : 'www', '/request/popular' : 'popular', '/request/search' : 'search', '/request/stream' : 'stream'} www = Directory(os.path.join(os.path.dirname(__file__), 'www')) def __init__(self): super().__init__() self.client = Client() self.client.init() self._cache = {} self._cache['streams'] = {} def _respond_json(self, data, response): response.headers['Content-Type'] = 'application/json; charset=UTF-8' response.body.append(json.dumps(data).encode('utf-8')) def _bad_request(self, message, response): response.status = 400 response.message = 'ERROR' response.headers['Content-Type'] = 'application/json; charset=UTF-8' response.body.append(json.dumps({'status' : 'error', 'result' : message}).encode('utf-8')) def popular(self, request, response): if not 'popular' in self._cache: self._cache['popular'] = (time.time(), [song.export() for song in self.client.popular()]) if time.time() - self._cache['popular'][0] > 7200: self._cache['popular'] = (time.time(), [song.export() for song in self.client.popular()]) self._respond_json({'status' : 'success', 'result' : self._cache['popular'][1]}, response) def search(self, request, response): if not 'type' in request.query: request.qery['type'] = [SEARCH_TYPE_SONGS] if 'query' in request.query: if not request.query['type'][0] in (Client.SONGS, Client.ALBUMS, Client.ARTISTS): self._bad_request('unknown type', response) else: result = [object.export() for object in self.client.search(request.query['query'][0], request.query['type'][0])] self._respond_json({'status' : 'success', 'result' : result}, response) else: self._bad_request('missing query argument', response) def stream(self, request, response): song = Song.from_export(json.loads(request.query['song'][0]), self.client.connection) if song.id in self._cache['streams']: stream, cache = self._cache['streams'][song.id] else: stream = song.stream cache = Cache(stream.data, stream.size) self._cache['streams'][song.id] = stream, cache if 'Range' in request.headers: response.status = 206 start_byte, end_byte = request.headers['Range'].replace('bytes=', '').split('-') if start_byte: start_byte = int(start_byte) else: start_byte = 0 if end_byte: end_byte = int(end_byte) else: end_byte = stream.size cache.offset = start_byte if 'download' in request.query: response.headers['Content-Disposition'] = 'attachment; filename="{} - {} - {}.mp3"'.format(song.name, song.album.name, song.artist.name) response.headers['Accept-Ranges'] = 'bytes' response.headers['Content-Type'] = stream.data.info()['Content-Type'] response.headers['Content-Length'] = str(stream.size) response.headers['Content-Range'] = 'bytes {}-{}/{}'.format(start_byte, end_byte, stream.size) response.body = FileWrapper(cache) else: cache.reset() if 'download' in request.query: response.headers['Content-Disposition'] = 'attachment; filename="{} - {} - {}.mp3"'.format(song.name, song.album.name, song.artist.name) response.headers['Accept-Ranges'] = 'bytes' response.headers['Content-Type'] = stream.data.info()['Content-Type'] response.headers['Content-Length'] = str(stream.size) response.body = FileWrapper(cache)
class Grooveshark(Application): __URLS__ = { "/desktop/.*|/icons/.*": "www", "/request/popular": "popular", "/request/search": "search", "/request/stream": "stream", } www = Directory(os.path.join(os.path.dirname(__file__), "www")) def __init__(self): super().__init__() self.client = Client() self.client.init() self._cache = {} self._cache["streams"] = {} def _respond_json(self, data, response): response.headers["Content-Type"] = "application/json; charset=UTF-8" response.body.append(json.dumps(data).encode("utf-8")) def _bad_request(self, message, response): response.status = 400 response.message = "ERROR" response.headers["Content-Type"] = "application/json; charset=UTF-8" response.body.append(json.dumps({"status": "error", "result": message}).encode("utf-8")) def popular(self, request, response): if "popular" not in self._cache: self._cache["popular"] = (time.time(), [song.export() for song in self.client.popular()]) if time.time() - self._cache["popular"][0] > 7200: self._cache["popular"] = (time.time(), [song.export() for song in self.client.popular()]) self._respond_json({"status": "success", "result": self._cache["popular"][1]}, response) def search(self, request, response): if "type" not in request.query: request.query["type"] = [SEARCH_TYPE_SONGS] if "query" in request.query: if not request.query["type"][0] in (Client.SONGS, Client.ALBUMS, Client.ARTISTS): self._bad_request("unknown type", response) else: result = [ object.export() for object in self.client.search(request.query["query"][0], request.query["type"][0]) ] self._respond_json({"status": "success", "result": result}, response) else: self._bad_request("missing query argument", response) def stream(self, request, response): song = Song.from_export(json.loads(request.query["song"][0]), self.client.connection) if song.id in self._cache["streams"]: stream, cache = self._cache["streams"][song.id] else: stream = song.stream cache = Cache(stream.data, stream.size) self._cache["streams"][song.id] = stream, cache if "Range" in request.headers: response.status = 206 start_byte, end_byte = request.headers["Range"].replace("bytes=", "").split("-") if start_byte: start_byte = int(start_byte) else: start_byte = 0 if end_byte: end_byte = int(end_byte) else: end_byte = stream.size cache.offset = start_byte if "download" in request.query: response.headers["Content-Disposition"] = 'attachment; filename="{} - {} - {}.mp3"'.format( song.name, song.album.name, song.artist.name ) response.headers["Accept-Ranges"] = "bytes" response.headers["Content-Type"] = stream.data.info()["Content-Type"] response.headers["Content-Length"] = str(stream.size) response.headers["Content-Range"] = "bytes {}-{}/{}".format(start_byte, end_byte, stream.size) response.body = FileWrapper(cache) else: cache.reset() if "download" in request.query: response.headers["Content-Disposition"] = 'attachment; filename="{} - {} - {}.mp3"'.format( song.name, song.album.name, song.artist.name ) response.headers["Accept-Ranges"] = "bytes" response.headers["Content-Type"] = stream.data.info()["Content-Type"] response.headers["Content-Length"] = str(stream.size) response.body = FileWrapper(cache)
#I am using pygrooveshark so credit to who ever made that and stuff from subprocess import call, Popen from grooveshark import Client import random counter=0 directory='/home/yanni/music/' #im not using this but change it to whatever use_spotify=False groovclient=Client() groovclient.init() def playSong(song): if (use_spotify==False): try: result=groovclient.search(song, Client.SONGS).next() return Popen(["cvlc", "--play-and-exit", result.stream.url]) except: pass else: pass def playStreamUrl(url): return Popen(["cvlc", "--play-and-exit", url]) def playList(playlist_id, shuffle, repeat): #the id is an int, others are bool result=groovclient.playlist(playlist_id) songs=list(result.songs) if (shuffle==True): random.shuffle(songs, random.random) if (repeat==True): #yeah so I'm not quite sure how to _best_ implement this feature yet
class playerManager(object): def __init__(self): self.client = Client() self.client.init() self.sc = songs_controller() self.sc.clearSongsTable() vlc_args = [""] self.instance = vlc.libvlc_new(len(vlc_args),vlc_args) self.mlist = self.instance.media_list_new() self.player = self.instance.media_player_new() self.mlp = self.instance.media_list_player_new() self.mlp.set_media_player(self.player) self.mlp.set_media_list(self.mlist) self.em = self.player.event_manager() self.em.event_attach(vlc.EventType.MediaPlayerEndReached, self.songEnded) def pauseToggle(self): if self.isPlaying(): self.pause() else: self.play() def skip(self): self.addNextSong() self.nextSong() # Pull next song from DB and add to vlc_controller def addNextSong(self): row = self.sc.getHighest() self.addSongRow(row) # Adds a song to the media list from a sqlite row object def addSongRow(self, row): media = self.instance.media_new(row['Url']) media.set_meta(vlc.Meta.Title, row['Name']) media.set_meta(vlc.Meta.Artist, row['Artist']) print('\033[92m' + media.get_meta(vlc.Meta.Title) + " - " + \ media.get_meta(vlc.Meta.Artist) + '\033[0m' ) self.mlist.add_media(media) def count(self): return self.mlist.count() def isPlaying(self): return self.mlp.is_playing() def play(self): self.mlp.play() def pause(self): self.mlp.pause() def remove(self, index): self.mlist.remove_index(index) def songEnded(self, data): self.addNextSong() # self.nextSong() def nextSong(self): self.mlp.next() def currentSong(self): song = {} logging.info( "DERP") media = self.player.get_media() if media: song['name'] = media.get_meta(vlc.Meta.Title) song['artist'] = media.get_meta(vlc.Meta.Artist) song['album'] = media.get_meta(vlc.Meta.Album) song['image'] = media.get_meta(vlc.Meta.ArtworkURL) else: song['name'] = "no" song['artist'] = "f*****g" song['album'] = "media" song['image'] = "" logging.info(song) return song
class Grooveshark(Application): __URLS__ = { '/desktop/.*|/icons/.*': 'www', '/request/popular': 'popular', '/request/search': 'search', '/request/stream': 'stream' } www = Directory(os.path.join(os.path.dirname(__file__), 'www')) def __init__(self): super().__init__() self.client = Client() self.client.init() self._cache = {} self._cache['streams'] = {} def _respond_json(self, data, response): response.headers['Content-Type'] = 'application/json; charset=UTF-8' response.body.append(json.dumps(data).encode('utf-8')) def _bad_request(self, message, response): response.status = 400 response.message = 'ERROR' response.headers['Content-Type'] = 'application/json; charset=UTF-8' response.body.append( json.dumps({ 'status': 'error', 'result': message }).encode('utf-8')) def popular(self, request, response): if 'popular' not in self._cache: self._cache['popular'] = (time.time(), [ song.export() for song in self.client.popular() ]) if time.time() - self._cache['popular'][0] > 7200: self._cache['popular'] = (time.time(), [ song.export() for song in self.client.popular() ]) self._respond_json( { 'status': 'success', 'result': self._cache['popular'][1] }, response) def search(self, request, response): if 'type' not in request.query: request.query['type'] = [SEARCH_TYPE_SONGS] if 'query' in request.query: if not request.query['type'][0] in (Client.SONGS, Client.ALBUMS, Client.ARTISTS): self._bad_request('unknown type', response) else: result = [ object.export() for object in self.client.search( request.query['query'][0], request.query['type'][0]) ] self._respond_json({ 'status': 'success', 'result': result }, response) else: self._bad_request('missing query argument', response) def stream(self, request, response): song = Song.from_export(json.loads(request.query['song'][0]), self.client.connection) if song.id in self._cache['streams']: stream, cache = self._cache['streams'][song.id] else: stream = song.stream cache = Cache(stream.data, stream.size) self._cache['streams'][song.id] = stream, cache if 'Range' in request.headers: response.status = 206 start_byte, end_byte = request.headers['Range'].replace( 'bytes=', '').split('-') if start_byte: start_byte = int(start_byte) else: start_byte = 0 if end_byte: end_byte = int(end_byte) else: end_byte = stream.size cache.offset = start_byte if 'download' in request.query: response.headers[ 'Content-Disposition'] = 'attachment; filename="{} - {} - {}.mp3"'.format( song.name, song.album.name, song.artist.name) response.headers['Accept-Ranges'] = 'bytes' response.headers['Content-Type'] = stream.data.info( )['Content-Type'] response.headers['Content-Length'] = str(stream.size) response.headers['Content-Range'] = 'bytes {}-{}/{}'.format( start_byte, end_byte, stream.size) response.body = FileWrapper(cache) else: cache.reset() if 'download' in request.query: response.headers[ 'Content-Disposition'] = 'attachment; filename="{} - {} - {}.mp3"'.format( song.name, song.album.name, song.artist.name) response.headers['Accept-Ranges'] = 'bytes' response.headers['Content-Type'] = stream.data.info( )['Content-Type'] response.headers['Content-Length'] = str(stream.size) response.body = FileWrapper(cache)
# -*- coding:utf-8 -*- # # Copyright (C) 2012, Maximilian Köhl <*****@*****.**> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import print_function import subprocess from grooveshark import Client client = Client() client.init() for song in client.popular(): print(song) subprocess.call(['mplayer', song.stream.url])
import nltk import nlpy import en import psw import gapi import player songPlayer = player.Player() player.init() import subprocess from grooveshark import Client songClient = Client() songClient.init() from sets import Set def matchWord(tokens, words): s = Set(tokens).intersection(Set(words)) if len(s) > 0: return [(w, 1.0, w) for w in s] else: from nltk.metrics import distance import operator result = [] for token in Set(tokens): vals = { w: (1.0 - float(distance.edit_distance(token, w)) /
#mongo = PyMongo(app) MONGO_URL = os.environ.get('MONGOHQ_URL') if MONGO_URL: # Get a connection conn = pymongo.Connection(MONGO_URL) # Get the database db = conn[urlparse(MONGO_URL).path[1:]] else: # Not on an app with the MongoHQ add-on, do some localhost action conn = pymongo.Connection('localhost', 27017) db = conn['someapps-db'] gsClient = Client() gsClient.init() gsClient.init_token() gsClient.init_queue() @app.route('/') def hello(): post = {"test": "tes1"} db.abc.insert(post) return 'Hello World!' @app.route('/ooh') def hii(): post_id = db.abc.find_one() return str(post_id)
def addSongBySourceType(self, rawData): """Add song that does not yet have a stream url""" client = Client() client.init() streamUrl = client.getStreamID(rawData['SongID'], rawData['ArtistID']) self.addSong(rawData['song'], rawData['artist'], streamUrl)
MONGO_URL = os.environ.get('MONGOHQ_URL') if MONGO_URL: # Get a connection conn = pymongo.Connection(MONGO_URL) # Get the database db = conn[urlparse(MONGO_URL).path[1:]] else: # Not on an app with the MongoHQ add-on, do some localhost action conn = pymongo.Connection('localhost', 27017) db = conn['someapps-db'] gsClient = Client() gsClient.init() gsClient.init_token() gsClient.init_queue() @app.route('/') def hello(): post = {"test" : "tes1"} db.abc.insert(post) return 'Hello World!' @app.route('/ooh') def hii(): post_id = db.abc.find_one() return str(post_id) '''
class MusicClient(object): """ Music client which wraps grooveshark api, allowing music to be streamed """ def __init__(self): self.client = Client() self.client.init() def stop(self): p = subprocess.Popen(["ps", "-A"], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.splitlines(): if "mplayer" in line: pid = int(line.split(None, 1)[0]) os.kill(pid, signal.SIGKILL) def find(self, search, index=None, max_results=15, type="Songs"): """ Find a song via grooveshark api search. Args: search (string): song title to search for. index (None, int): index value of song selection. max_results (int, optional): number of results to return from the search. Returns: result (tuple, grooveshark.classes.Song, list): song result list """ song_results = list(self.client.search(search, type=type))[:max_results] if isinstance(index, int): index = int(index) result_count = len(song_results) if -1 < index < result_count: result = song_results[index] else: result = [] else: result = song_results return result def youtube(self, url): """ Build the pafy youtube object Args: url (string): the youtube url Returns: result Pafy youtube """ youtube = pafy.new(url) return youtube def file(self, url): """ Build a loose song dict from a url Args: url (string): the file url Returns: result song (dict) """ song = { "title": '', "artist": '', "album": '', "track": '', "url": url, "duration": '', "queued_by": '' } return song def search(self, search): """ Returns formatted string list of song results from the search term provided Args: (string): Formatted list of song search results """ search_results = "\n".join([ repr(index) + "." + song.name + " by " + song.artist.name + " from " + song.album.name for index, song in enumerate(self.find(search), start=1) ]) search_results = search_results if search_results else "No results found for {0}".format( search) return search_results def radio(self, genre): return self.client.radio(genre) def play(self, song): """ Play song subprocess callback, via mplayer Args: queued (int): flag for tracking whether a queued song is playing song (dict): song dictionary retrieved from queue list """ popen_object = None print("Playing " + song["title"] + " by " + song["artist"]) FNULL = open(os.devnull, "w") popen_object = subprocess.Popen(["mplayer", song["url"]], shell=False, stdout=FNULL, stderr=subprocess.STDOUT, bufsize=1) while popen_object.poll() is None: time.sleep(1.0)
import nltk import nlpy import en import psw import gapi import player songPlayer = player.Player() player.init() import subprocess from grooveshark import Client songClient = Client() songClient.init() from sets import Set def matchWord(tokens, words): s = Set(tokens).intersection(Set(words)) if len(s)>0: return [(w,1.0,w) for w in s] else: from nltk.metrics import distance import operator result = [] for token in Set(tokens): vals = {w : (1.0-float(distance.edit_distance(token, w))/float(max(len(token),len(w)))) for w in words} sortedvals = sorted(vals.iteritems(), key=operator.itemgetter(1),reverse=True) result.append( (token, sortedvals[0][1], sortedvals[0][0]) )
import nltk import nlpy import en import psw import gapi import player songPlayer = player.Player() player.init() import subprocess from grooveshark import Client songClient = Client() ''' songClient.init() ''' from sets import Set def matchWord(tokens, words): s = Set(tokens).intersection(Set(words)) if len(s)>0: return [(w,1.0,w) for w in s] else: from nltk.metrics import distance import operator result = [] for token in Set(tokens): vals = {}
from django.shortcuts import render_to_response from django.http import HttpResponse, HttpResponseBadRequest from wsgiref.util import FileWrapper import simplejson as json import time from services.cache import Cache from grooveshark import Client from grooveshark.classes.song import Song client = Client() client.init() _cache = {} _cache['streams'] = {} def index(request): return render_to_response("index.html") def popular(request): if 'popular' not in _cache: _cache['popular'] = ( time.time(), [song.export() for song in client.popular()]) if time.time() - _cache['popular'][0] > 7200: _cache['popular'] = ( time.time(),
class MusicClient(object): """ Music client which wraps grooveshark api, allowing music to be streamed """ def __init__(self): self.client = Client() self.client.init() def stop(self): p = subprocess.Popen(["ps", "-A"], stdout=subprocess.PIPE) out, err = p.communicate() for line in out.splitlines(): if "mplayer" in line: pid = int(line.split(None, 1)[0]) os.kill(pid, signal.SIGKILL) def find(self, search, index=None, max_results=15, type="Songs"): """ Find a song via grooveshark api search. Args: search (string): song title to search for. index (None, int): index value of song selection. max_results (int, optional): number of results to return from the search. Returns: result (tuple, grooveshark.classes.Song, list): song result list """ song_results = list(self.client.search(search, type=type))[:max_results] if isinstance(index, int): index = int(index) result_count = len(song_results) if -1 < index < result_count: result = song_results[index] else: result = [] else: result = song_results return result def youtube(self, url): """ Build the pafy youtube object Args: url (string): the youtube url Returns: result Pafy youtube """ youtube = pafy.new(url) return youtube def file(self, url): """ Build a loose song dict from a url Args: url (string): the file url Returns: result song (dict) """ song = { "title": '', "artist": '', "album": '', "track": '', "url": url, "duration": '', "queued_by": '' } return song def search(self, search): """ Returns formatted string list of song results from the search term provided Args: (string): Formatted list of song search results """ search_results = "\n".join([repr(index) + "." + song.name + " by " + song.artist.name + " from " + song.album.name for index, song in enumerate(self.find(search), start=1)]) search_results = search_results if search_results else "No results found for {0}".format(search) return search_results def radio(self, genre): return self.client.radio(genre) def play(self, song): """ Play song subprocess callback, via mplayer Args: queued (int): flag for tracking whether a queued song is playing song (dict): song dictionary retrieved from queue list """ popen_object = None print("Playing " + song["title"] + " by " + song["artist"]) FNULL = open(os.devnull, "w") popen_object = subprocess.Popen(["mplayer", song["url"]], shell=False, stdout=FNULL, stderr=subprocess.STDOUT, bufsize=1) while popen_object.poll() is None: time.sleep(1.0)