Example #1
0
class PlayScreen(Screen):
    background = ObjectProperty(None)
    instructor = ObjectProperty(None)
    pygame.init()
    pygame.display.set_mode((200, 100))

    naturePlaylist = []
    classicalPlaylist = []
    motivationalPlaylist = []

    global modelDict

    with open('data.json', 'r') as fp:
        modelDict = json.load(fp)

    def changeBackground(self):
        """Simple Function to Change the Background of the App when a new song loads or on back press"""
        self.path = "background/"
        self.bgList = (glob.glob("backgrounds/*"))
        self.randomSelect = random.choice(self.bgList)
        self.fullPath = self.randomSelect
        self.background.source = self.fullPath

    def pauseSong(self):
        """Simple Function to Change the Background of the App To Pause"""
        playing = pygame.mixer.music.get_busy
        if playing == True:
            pygame.mixer.music.pause()
        else:
            pass

    def playSong(self):
        """Simple Function to select a playlist and select a random song from that playlist, then play it as a thread"""
        currentRoom = predict()

        genre = modelDict[currentRoom]

        currentPlaylist = genre + "playlist"
        playlistURL = random.choice(currentPlaylist)

        self.api = SoundcloudAPI()

        self.playlist = self.api.resolve(playlistURL)

        assert type(self.playlist) is Playlist
        self.track = random.choice(self.playlist.tracks)

        self.filename = f'music/{self.track.artist}-{self.track.title}.mp3'
        with open(self.filename, 'wb+') as fp:
            self.track.write_mp3_to(fp)

        self.songList = (glob.glob("music/*"))
        self.mySong = self.songList[0]

        self.changeBackground()

        pygame.mixer.music.load(self.mySong)
        pygame.mixer.music.play(0)
        os.remove(self.mySong)
Example #2
0
def main(link):
    api = SoundcloudAPI()
    track = api.resolve(link)
    assert type(track) is Track

    artist = track.artist
    title = track.title
    return title, artist
Example #3
0
def get_soundcloud_playlist(playlist_url):
    api = SoundcloudAPI()
    print(playlist_url)
    rp = api.resolve(playlist_url)
    if "track" in str(type(rp)).lower():
        return [rp.permalink_url]
    else:
        soundcloud_urls = [track.permalink_url for track in rp.tracks]
    return soundcloud_urls
Example #4
0
def download_soundcloud(SOUND_URL):
    global TRACK_ARTIST
    global TRACK_ARTIST
    global SOUND_FILE_NAME

    soundcolud_api = SoundcloudAPI()
    track = soundcolud_api.resolve(SOUND_URL)
    assert type(track) is Track

    TRACK_ARTIST = track.artist
    TRACK_TITLE = track.title
    SOUND_FILE_NAME = 'working_directory/source_files/SOURCE_SOUND.mp3'
    print(SOUND_FILE_NAME)
    with open(SOUND_FILE_NAME, 'wb+') as fp:
        track.write_mp3_to(fp)
Example #5
0
def download_all_podcast(url):
    url=url
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, 'lxml')
    pd_title = soup.find_all('h2', class_='entry-title')
    global epi
    for j in reversed(range(0, len(pd_title))):
        tmp_ttitle = pd_title[j].text.replace(" ", "_")
        
        epi_url =pd_title[j].find('a').get('href')
        epi_headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
        epi_response = requests.get(epi_url, headers=epi_headers)
        epi_soup = BeautifulSoup(epi_response.text, 'lxml')
        epi_dl = epi_soup.find_all('div', class_='entry_content')
        
        snd_dl=epi_dl[0].find('a', href=re.compile('soundcloud'))
        mp3_dl = epi_dl[0].find('a', href=re.compile('mp3'))

        if (snd_dl is not None):
            #
            # This code will run if there is a Soundcloud link
            #
            print(str(epi) + '_'+ tmp_ttitle)
            print(snd_dl.get('href'))
            api = SoundcloudAPI()  # never pass a Soundcloud client ID that did not come from this library
            track = api.resolve(snd_dl.get('href'))
            with open(str(epi) + '_'+ tmp_ttitle + '.mp3', 'wb+') as fp:
                track.write_mp3_to(fp)

        elif (mp3_dl is not None):
            #
            # This code will run if there is an Mp3 link
            #
            print(str(epi) + '_'+ tmp_ttitle)
            print(mp3_dl.get('href'))
            doc = requests.get(mp3_dl.get('href'))
            with open(str(epi) + '_'+ tmp_ttitle + '.mp3', 'wb') as f:
                f.write(doc.content)
        else:
            #
            # This code will run if there No Link
            #
            print('sorry no audio file found')
        
        epi+=1
    print('\n')
def download_soundcloud_mp3(sender, data):
    with window("File downloader"):
        api = SoundcloudAPI()
        track =  api.resolve(get_value("URL3"))
        assert type(track) is Track
        image_url = track.artwork_url
        r = requests.get(image_url, stream=True)
        fn = f'./audios/{track.artist} - {track.title}.mp3'
        fn_artwork = f'./artworks/{track.artist} - {track.title}_artwork.jpeg'
        with open(fn, 'wb+') as fp:
            track.write_mp3_to(fp)
            log_info(logger="logger_general", message="Downloaded: " + fn)
            if r.status_code == 200:
                r.raw.decode_content = True
                with open(fn_artwork, 'wb') as f:
                    shutil.copyfileobj(r.raw, f)
                    log_info(logger="logger_general", message="Artwork downloaded as: " + fn_artwork)
                    draw_image("artwork_image", f'./artworks/{track.artist} - {track.title}_artwork.jpeg', [0, 0], [120, 120])
            else:
                log_error(logger="logger_general", message="Couldn't fetch artwork")
def download_soundcloud_playlist(sender, data):
    with window("File downloader"):

        api = SoundcloudAPI()
        playlist = api.resolve(get_value("URL3"))
        assert type(playlist) is Playlist
        playlist_artwork= playlist.artwork_url
        fn_playlist_artwork = f'./artworks/{playlist.title}_artwork.jpeg'
        r = requests.get(playlist_artwork, stream=True)
        if r.status_code == 200:
            r.raw.decode_content=True
            with open(fn_playlist_artwork, 'wb') as f:
                shutil.copyfileobj(r.raw, f)
                log_info(logger="logger_general", message="Playlist artwork downloaded as: " + fn_playlist_artwork)
        else:
            log_error(logger="logger_general", message="Couldn't fetch playlist artwork")

        for track in playlist.tracks:
            fn = f'./audios/{track.artist} - {track.title}.mp3'
            log_info(logger="logger_general", message="Downloaded: " + fn)
            with open(fn, 'wb+') as fp:
                track.write_mp3_to(fp)
Example #8
0
def get_playlist(playlist_name):
    playlist_name_formatted = playlist_name.replace(" ", "-").replace("'", "")
    url = 'https://soundcloud.com/tessssa8/sets/' + playlist_name_formatted
    try:
        dir_path = os.curdir + f"/mp3_files/{playlist_name_formatted}"
        os.mkdir(dir_path)
    except OSError:
        return 1
    try:
        api = SoundcloudAPI()
        playlist = api.resolve(url)

        assert type(playlist) is Playlist

        for track in playlist.tracks:
            filename = os.curdir + f'/mp3_files/{playlist_name_formatted}/{track.artist} - {track.title}.mp3'
            print(filename)
            with open(filename, 'wb+') as fp:
                track.write_mp3_to(fp)

        return 0
    except Exception:
        return 1
Example #9
0
    playlists_table[i].split(" ")[0] for i in range(len(playlists_table))
]

folder_names = [
    playlists_table[i].split(" ")[1] for i in range(len(playlists_table))
]

print(np.array(list(zip(folder_names, playlists))))

api = SoundcloudAPI()

for folder_name, playlist_url in zip(folder_names, playlists):

    print(playlist_url)

    playlist = api.resolve(playlist_url)

    for track in playlist.tracks:
        filename = f'{track.artist} - {track.title}'
        for i in filename:
            if ord(i) not in np.concatenate([
                    np.arange(49, 58),
                    np.arange(65, 91),
                    np.arange(97, 123), [32, 45, 97]
            ]):
                filename = filename.replace(i, "")
            if ord(i) == 32:
                filename = filename.replace(i, "_")
        filename = f"{folder_name}/" + filename + '.mp3'
        if os.path.isfile(filename):
            pass
Example #10
0
Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1mEk4395OF41qJhgVXcM00wLkfO3DuTLF
"""

# !pip install soundcloud-lib

from sclib import SoundcloudAPI, Track, Playlist
from IPython.display import Image, display_jpeg

api = SoundcloudAPI()

# 任意のtrackURL
track = api.resolve('https://soundcloud.com/brandnewidolsociety/romeosheart')

filename = f'./{track.artist} - {track.title}.mp3'

# trackをmp3で保存
with open(filename, 'wb+') as fp:
    track.write_mp3_to(fp)

# trackの持つプロパティをすべて表示
track = api.resolve(
    'https://soundcloud.com/orco-350884854/diamond-dustprodweirdove')
array = dir(track)
for index, item in enumerate(array):
    print('■' + str(index) + ':' + item)
    x = 'track.' + item
    print(eval(x))
Example #11
0
import sys
from sclib import SoundcloudAPI, Track, Playlist

api = SoundcloudAPI(
)  # never pass a Soundcloud client ID that did not come from this library

videourl = sys.argv[1] + ''
track = api.resolve(videourl)

assert type(track) is Track

#filename = f'./{track.artist} - {track.title}.mp3'
attrs = dir(track)
print(track.artwork_url)

print(track.get_stream_url())
print(track.title)
print(track.artist)
print(track.tag_list)
print(track.id)
'''
print(track.album_artwork)
print(track.artwork_url)
print(track.tag_list)

with open(filename, 'wb+') as fp:
    track.write_mp3_to(fp)
'''
Example #12
0
from sclib import SoundcloudAPI, Track
from io import BytesIO

api = SoundcloudAPI()
urls = ['https://soundcloud.com/nittigritti/lights-nitti-gritti-remix-1']
for url in urls:
    track = api.resolve(url)
    file = BytesIO()
    size = file.__sizeof__()
    track.write_mp3_to(file)
from sclib import SoundcloudAPI, Track, Playlist
from urllib.request import urlopen
import json
import unicodedata
import re
import shout
import io
import time
import random
import datetime
import os 

api = SoundcloudAPI()

playlist = api.resolve(os.environ.get('SOUNDCLOUD_PLAYLIST'))
s = shout.Shout()
print("Using libshout version %s" % shout.version())
s.host = os.environ.get('ICECAST_HOST')
s.password = os.environ.get('ICECAST_PASSWORD')
s.mount = os.environ.get('ICECAST_MOUNTPOINT','/stream')
s.format = 'mp3'
s.url = os.environ.get('ICECAST_URL', "unknown")
s.genre = os.environ.get('ICECAST_GENRE', "unknown")
s.public = os.environ.get('ICECAST_PUBLIC', 0) 
s.name = os.environ.get('ICECAST_STREAM_NAME', "unknown")
s.description = os.environ.get('ICECAST_STREAM_DESCRIPTION', "No Description")
s.open()

def get_url(url):
    return urlopen(url).read()
Example #14
0
def shell():
    os.system("clear")

    while True:
        print(ascii[random.randint(0, len(ascii) - 1)])

        print("1. mp4 (Youtube)")
        print("2. mp3 (Youtube + Soundcloud)")
        print("3. Exit")

        try:
            inp = input()
            if int(inp) == 1:
                os.system("clear")
                print(
                    "[+] Incolla il link youtube di una playlist o di una canzone."
                )
                url = input("")
                os.system(
                    "mkdir mp4; cd mp4; youtube-dl -i -f mp4 --yes-playlist --no-check-certificate "
                    + url)
                time.sleep(5)
                os.system("clear")
                print("\n\n\n[+] Tutto fatto!")
                continue
            elif int(inp) == 2:
                os.system("clear")
                print(
                    "[+] Incolla il link youtube o soundcloud di una playlist o di una canzone."
                )
                url = input("")
                if "soundcloud" in url:
                    api = SoundcloudAPI()
                    if "/sets/" in url:
                        playlist = api.resolve(url)
                        for track in playlist.tracks:
                            track_artist = str(track.artist)
                            track_title = str(track.title)
                            if "/" in track_title:
                                track_title = track_title.replace("/", "+")
                            if "/" in track_artist:
                                track_artist = track_artist.replace("/", "+")
                            filename = f'./mp3/{track_artist} - {track_title}.mp3'
                            try:
                                with open(filename, 'wb+') as fp:
                                    try:
                                        track.write_mp3_to(fp)
                                    except Exception as e:
                                        print(
                                            "[-] {} - {}       non puo essere scaricata"
                                            .format(track_artist, track_title))
                                        continue
                            except OSError as e:
                                filename = f'./mp3/{track.artist} - {track.title[:8]}.mp3'
                                with open(filename, 'wb+') as fp:
                                    track.write_mp3_to(fp)
                        print("[+] Tutto finito!")
                        continue
                    else:
                        track = api.resolve(url)
                        track_artist = str(track.artist)
                        track_title = str(track.title)
                        if "/" in track_title:
                            track_title = track_title.replace("/", "+")
                        if "/" in track_artist:
                            track_artist = track_artist.replace("/", "+")
                        filename = f'./mp3/"{track_artist} - {track_title}.mp3"'
                        try:
                            with open(filename, 'wb+') as fp:
                                try:
                                    track.write_mp3_to(fp)
                                except Exception as e:
                                    print(
                                        "[-] {} - {}       non puo essere scaricata"
                                        .format(track_artist, track_title))
                                    continue
                        except OSError as e:
                            filename = f'./mp3/{track.artist} - {track.title[:8]}.mp3'
                            with open(filename, 'wb+') as fp:
                                track.write_mp3_to(fp)
                            print("[+] Tutto finito!")
                            continue
                os.system(
                    "mkdir mp4; cd mp4; youtube-dl -i -f mp4 --yes-playlist --no-check-certificate "
                    + url)
                time.sleep(5)
                print("[+] Tutto fatto, converto ora i file in mp3")
                foldermp3 = "./mp3/"
                foldermp4 = "./mp4/"
                os.system("mkdir mp3")
                counter = 0
                for file in os.listdir(foldermp4):
                    mp4 = VideoFileClip(foldermp4 + file)
                    mp3 = mp4.audio
                    mp3.write_audiofile(foldermp3 +
                                        (file.split(".mp4")[0] + ".mp3"))
                    mp3.close()
                    counter += 1
                if counter == len(os.listdir("mp4")):
                    os.system("clear")
                    os.system("rm -r " + foldermp4)
                    os.system("clear")
                    for file in os.listdir(foldermp3):
                        os.system('mv "{}" "{}"'.format(
                            foldermp3 + str(file),
                            foldermp3 + str(file[:-16] + ".mp3")))
                    print("[+] Tutto finito!")
            elif int(inp) == 3:
                os.system("clear")
                print("Auf wiedersehen!")
                exit()
            else:
                os.system("clear")
                print(
                    "Cio che hai digitato non ? incluso nelle possibili scelte."
                )

        except Exception as e:
            os.system("clear")
            print("[-] Qualcosa ? andato storto, riprova :(")
            continue
Example #15
0
class VlcPlayer():
    def __init__(self):
        self.saved_softvolume = -1
        self.saved_hardvolume = -1
        self.instance = vlc.Instance("--no-video")
        self.player = self.instance.media_player_new()
        self.sayplayer = self.instance.media_player_new()
        self.list_player = self.instance.media_list_player_new()
        self.list_player.set_media_player(self.player)
        if sclib_available:
            self.sc_api = SoundcloudAPI()

    def playytb(self, vid):
        self.play(vid2youtubeMRL(vid))

    def playytbLink(self, link):
        self.play(link2youtubeMRL(link))

    def playscloud(self, identifier):
        if not sclib_available:
            return (False)
        #Url of the format: https://soundcloud.com/aries_ix/sayonara
        url = "https://souncloud.com" + identifier
        track = self.sc_api.resolve(url)
        try:
            assert type(track) is Track
        except AssertionError as error:
            logger.debug(error)

        filename = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                "download.mp3")
        with open(filename, "wb+") as fp:
            track.write_mp3_to(fp)
        self.play(filename)

    def play(self, mrl_string):
        self.mrl = mrl_string.split(";")
        media_list = self.instance.media_list_new(self.mrl)
        self.list_player.set_media_list(media_list)
        self.list_player.play()
        self.softvolume(100, self.player)

    def playtunein(self, query_name):
        base_url = "http://opml.radiotime.com/Search.ashx?query=" + \
            urllib.parse.urlencode(query_name)
        resp = requests.get(base_url)
        resp_list = xml.dom.minidom.parse(resp)
        resp_list = resp_list.getElementsByTagName("outline")
        if not resp_list:
            return

        playing_mrl = resp_list[0].getAttribute("URL")
        self.play(playing_mrl)
        # playing_mrl = requests.get(playing_url)

    def next(self):
        if self.is_playing():
            self.list_player.next()

    def previous(self):
        if self.is_playing():
            self.list_player.previous()

    def restart(self):
        if self.is_playing():
            self.list_player.previous()
            time.sleep(0.01)
            self.list_player.next()

    def shuffle(self):
        if self.is_playing():
            self.list_player.stop()
            random.shuffle(self.mrl)
            media_list = self.instance.media_list_new(self.mrl)
            self.list_player.set_media_list(media_list)
            self.list_player.play()
            self.softvolume(100, self.player)

    def pause(self):
        if self.is_playing():
            self.list_player.pause()

    def resume(self):
        # pause works like a button, thus doing both pause and resume
        if not self.is_playing():
            self.list_player.pause()

    def stop(self):
        self.list_player.stop()

    def wait_till_end(self, pl):
        playing = set(
            [vlc.State.Playing, vlc.State.Buffering, vlc.State.Opening])
        # wait some time to give vlc a chance to start up
        time.sleep(0.3)
        time_left = True
        while time_left == True:
            pstate = pl.get_state()
            if pstate not in playing:
                time_left = False
            # print("Sleeping for audio output")
            time.sleep(0.1)

    def is_playing(self):
        return self.list_player.is_playing()

    def beep(self, mrl):
        self.save_softvolume()
        self.say(mrl, False)

    def say(self, mrl, wait_restore=True):
        self.save_softvolume()
        if (self.list_player.is_playing()):
            # reduce volume to 20% of the current volume
            self.softvolume(int(0.2 * self.saved_softvolume), self.player)
            time.sleep(0.2)
        # play additional stream via sayplayer
        media = self.instance.media_new(mrl)
        self.sayplayer.set_media(media)
        self.sayplayer.play()
        if self.saved_softvolume > 0:
            self.softvolume(self.saved_softvolume, self.sayplayer)
        else:
            self.softvolume(100, self.sayplayer)
        if wait_restore:
            self.wait_till_end(self.sayplayer)
            self.restore_softvolume()

    def volume(self, val):
        return mixer.volume(val)

    def softvolume(self, val, pl):
        if (val is None):
            absvol = mixer.volume(None)
            sf = pl.audio_get_volume()
            # sometimes the softvolume is bigger than 100 while hw volume is 100, catch that
            return min(100, int(sf * 100 / absvol))
        elif ((isinstance(val, int) or val.isdigit()) and (int(val) <= 100)
              and (int(val) >= 0)):
            p = int(val)
            absvol = mixer.volume(None)
            softvol = min(absvol, round(absvol * p / 100))
            pl.audio_set_volume(softvol)
            return (softvol)
        else:
            raise Exception('Invalid argument to softvolume: ' + str(val))

    def save_softvolume(self):
        self.saved_softvolume = self.softvolume(None, self.player)
        return self.saved_softvolume

    def restore_softvolume(self):
        if (self.saved_softvolume >= 0):
            self.softvolume(self.saved_softvolume, self.player)
        return self.saved_softvolume

    def save_hardvolume(self):
        self.saved_hardvolume = mixer.volume(None)
        return self.saved_hardvolume

    def restore_hardvolume(self):
        if (self.saved_hardvolume >= 0):
            mixer.volume(self.saved_hardvolume)
        return self.saved_hardvolume
Example #16
0
from sclib import SoundcloudAPI, Track, Playlist


fileName = "shortcode.txt"
shortCodeFile  = open(fileName, "r")
shortCode = shortCodeFile.readline()

api = SoundcloudAPI()  # never pass a Soundcloud client ID that did not come from this library

track = api.resolve(shortCode)

# https://soundcloud.com/salehhadad/undefeated-will?ref=clipboard&p=i&c=0

assert type(track) is Track

filename = f'./media/soundcloudFile.mp3'

with open(filename, 'wb+') as fp:
    track.write_mp3_to(fp)


shortCodeFile.close()
Example #17
0
from bs4 import BeautifulSoup
import os

from urllib.request import urlopen

from sclib import SoundcloudAPI, Track, Playlist

URL = input()
HEADERS = {
    'User-Agent':
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36 OPR/72.0.3815.487',
    'accept': '*/*'
}

api = SoundcloudAPI()
track = api.resolve(URL)


def get_html(URL, params=None):
    r = requests.get(URL, headers=HEADERS, params=params)
    return r


def get_content(html):
    assert type(track) is Track
    filename = f'./{track.artist} - {track.title}.mp3'
    with open(filename, 'wb+') as fp:
        track.write_mp3_to(fp)

    soup = BeautifulSoup(html, 'html.parser')
    img_url = soup.find('meta', property='og:image').get('content')