def music_setting(self, stat): response = "" try: import sys sys.path.append(self.UTILS_DIR) from musicplayer import MusicPlayer mp = MusicPlayer() player_setting = mp.get_player_setting()["status"].strip().lower() if player_setting != "close": if "pause" in stat: stat = "pause" response = "Music is Paused..." elif "skip" in stat or "next" in stat: stat = "skip" response = "Skipping..." elif "play" in stat and "stop" not in stat: stat = "Playing" response = "Now Playing..." elif "close" in stat or "stop" in stat: stat = "close" response = "Closing Music Player..." else: stat = "" if stat: mp.player_status(stat) return f'{choice(self._get_commands("acknowledge response"))} {response}' except Exception: self.Log("Music Setting Error.") return response
def __init__(self): pygame.init() self.timer=0 self.music=MusicPlayer() #Different sprites: self.gamesprites=[] self.menu1sprites=[] self.menu2sprites=[] self.new_objects=[] #Stores all buttons: self.buttons=[] btn1=Button(280,250,"help") btn2=Button(280,100,"start") self.buttons.append(btn1) self.buttons.append(btn2) self.menu1sprites.extend(self.buttons) #Create cursor and container for selected object: self.cursor=Cursor(); self.menu1sprites.append(self.cursor) self.selected=None #Append game objects: self.player=Player(150,150) self.gamesprites.append(self.player) self.once=True self.once2=True self.failed=False
class SmashMusic: def __init__(self): self.stageNames = ["Menu", "PrincessPeachsCastle", "RainbowCruise", "KongoJungle", "JungleJapes", "GreatBay", "Temple", "YoshisStory", "YoshisIsland", "FountainOfDreams", "GreenGreens", "Corneria", "Venom", "Brinstar", "BrinstarDepths", "Onett", "Fourside", "MuteCity", "BigBlue", "PokemonStadium", "PokeFloats", "MushroomKingdom", "MushroomKingdomII", "IcicleMountain", "FlatZone", "Battlefield", "FinalDestination", "DreamLand", "YoshisIsland64", "KongoJungle64"] self.playerSet = False self.gamePlayed = False self.setStage(-1) self.generateLocationsFile() def generateLocationsFile(self): os.makedirs(memoryWatcherPath, exist_ok=True) with open(memoryWatcherPath + "/Locations.txt", "w") as dest: with open(scriptPath + "/locations/GALE01.txt") as origin: for line in origin: output = line[:line.find('#')] if output != "": dest.write(output + '\n') def run(self): watch = MemoryWatcher(memoryWatcherPath + "/MemoryWatcher") for address, data in watch: #get stage id if address == "804D6CAC": stage = data[2] stageStart = data[3] if stageStart == 1: self.setStage(stage) #check if out of game #by checking for removal of current musicID elif address == "8049e760": if data == b'\xff\xff\xff\xff': #SSBM clears the current musicID before setting it for the first time if self.gamePlayed: self.setStage(-1) self.gamePlayed = True def stageIDtoName(self, stageID): return self.stageNames[stageID+1] def setStage(self, stageID): if self.playerSet: self.player.stop() self.player = MusicPlayer(self.stageNames) self.player.setPlaylist(self.stageIDtoName(stageID)) self.player.start() self.playerSet = True print("stageID: " + str(stageID))
def setStage(self, stageID): if self.playerSet: self.player.stop() self.player = MusicPlayer(self.stageNames) self.player.setPlaylist(self.stageIDtoName(stageID)) self.player.start() self.playerSet = True print("stageID: " + str(stageID))
def music_volume(self, volume): try: import sys sys.path.append(self.UTILS_DIR) from musicplayer import MusicPlayer mp = MusicPlayer() # change the directory to location of batch file to execute os.chdir(self.UTILS_DIR) mp.music_player_volume(volume) # get back to virtual assistant directory os.chdir(self.ASSISTANT_DIR) except Exception: self.Log("Music Volume Skill Error.")
def new_game(): root_widget.clear_widgets() game_widget = GameWidget() #level = x root_widget.add_widget(game_widget) root_widget.ids['game'] = game_widget lbl_fps = Label(pos_hint={'center_x': .95, 'center_y': .95}) root_widget.add_widget(lbl_fps) root_widget.ids['fps'] = lbl_fps lbl_score = Label(pos_hint={'center_x': .95, 'center_y': .90}) root_widget.add_widget(lbl_score) root_widget.ids['score'] = lbl_score musicplayer = MusicPlayer() musicplayer.start()
def new_game(self): self.clear_widgets() game_widget = GameWidget(self) #level = x self.add_widget(game_widget) self.ids['game'] = game_widget lbl_fps = Label(pos_hint={'center_x': .95, 'center_y': .95}) self.add_widget(lbl_fps) self.ids['fps'] = lbl_fps lbl_score = Label(pos_hint={'center_x': .95, 'center_y': .90}) self.add_widget(lbl_score) self.ids['score'] = lbl_score lbl_level = Label(pos_hint={'center_x': .95, 'center_y': .85}) self.add_widget(lbl_level) self.ids['level'] = lbl_level musicplayer = MusicPlayer() musicplayer.start()
def __init__(self, *, playlist: list = None, loopingState: PlaylistLoopingState = PlaylistLoopingState. NotLooping): self.player = MusicPlayer() self.playlist = [] #I want it to realize its a list, none wont do that self.state = PlaylistState.Uninitialized if playlist is not None: self.playlist = playlist self.state = PlaylistState.Start self.currentIndex = 0 self.loopState = loopingState
def setUp(self): # creating mock discord interactions self.textChannel = AsyncMock() self.textChannel2 = AsyncMock() self.voiceChannel = AsyncMock(discord.VoiceChannel) self.voiceChannel.connect.return_value = AsyncMock(discord.VoiceClient) self.voiceChannel2 = AsyncMock(discord.VoiceChannel) self.voiceChannel2.connect.return_value = AsyncMock( discord.VoiceClient) self.client = AsyncMock() # creating mock data interactions data = {'url': 'http://mock.url', 'title': 'Mock Youtube Video'} self.ytdl = Mock() self.ytdl.extract_info = Mock(return_value=data) # creating client self.player = MusicPlayer(self.client, self.ytdl)
def CreateWindow(self): music = MusicPlayer() music.player.play() windowInstance = Window()
def music_player(emotion_str): from musicplayer import MusicPlayer root = Tk() print('\nPlaying ' + emotion_str + ' songs') MusicPlayer(root, emotion_str) root.mainloop()
import pygame import time from musicplayer import MusicPlayer pygame.init() soitin=MusicPlayer() counter=0 while True: time.sleep(3) if counter>=2: print "playing" soitin.play_audio(2) counter=0 counter+=1 print soitin.has_ended()
class Engine(object): ''' Class that calculates things ''' def __init__(self): pygame.init() self.timer=0 self.music=MusicPlayer() #Different sprites: self.gamesprites=[] self.menu1sprites=[] self.menu2sprites=[] self.new_objects=[] #Stores all buttons: self.buttons=[] btn1=Button(280,250,"help") btn2=Button(280,100,"start") self.buttons.append(btn1) self.buttons.append(btn2) self.menu1sprites.extend(self.buttons) #Create cursor and container for selected object: self.cursor=Cursor(); self.menu1sprites.append(self.cursor) self.selected=None #Append game objects: self.player=Player(150,150) self.gamesprites.append(self.player) self.once=True self.once2=True self.failed=False def update_objects(self,mode): self.new_objects=[] #check mouse collisions: self.buttonselect() self.collisions(self.gamesprites) #Idea: all objects have their own update-method that can be called here! if(mode=="menu1"): for object in self.menu1sprites: object.update() elif(mode=="game"): if self.once==True: self.music.play_audio(2) self.once=False for object in self.gamesprites: object.update() if self.music.has_ended()==True: return 0 if (self.timer % 10) == 0: self.generate_collectible() self.timer+=1 elif(mode=="menu2"): for object in self.menu2sprites: object.update() if(self.player.lives<=0 and self.once2==True): self.player_dies() return self.player.lives def player_dies(self): self.failed=True self.music.stop_all() self.music.play_audio(0) self.once2=False def buttonselect(self): self.selected=None for button in self.buttons: if self.cursor.rect.colliderect(button.rect): button.select() self.selected=button else: button.deselect() def click(self): if self.selected!=None: self.music.play_audio(0) return self.selected.clicked_on() else: return None def generate_collectible(self): if (self.timer % 150) == 0 and self.timer > 500: x = random.randrange(400, 450, 5) p = -5 if (self.timer % 300) == 0 and self.timer > 100: x = random.randrange(10, 60, 5) p = -5 else: x = 230 + int(215 * sin(self.timer*0.1)) p = random.choice([1,5,10]) new=Collectible(p, 5, x) self.gamesprites.append(new) self.new_objects.append(new) def return_gamesprites(self): return self.gamesprites def return_menu1sprites(self): return self.menu1sprites def return_menu2sprites(self): return self.menu2sprites def return_new(self): return self.new_objects def return_player_lives(self): return self.player.lives def return_player_score(self): return self.player.score def calculate_end_score(self): lives=self.player.lives self.player.score+=lives*500 def collisions(self, things): if len(things) > 1: for thing in things[1:]: if things[0].rect.colliderect(thing.rect): things[0].score += thing.points if thing.points < 0: things[0].lives -= 1 things.remove(thing) thing.kill()
def sound(): from musicplayer import MusicPlayer app = MusicPlayer(root)
conf = json.load(open("conf.json")) # initialize the camera and grab a reference to the raw camera capture camera = PiCamera() camera.resolution = tuple(conf["resolution"]) camera.framerate = conf["fps"] camera.exposure_mode = "off" camera.shutter_speed = 12000 camera.awb_mode = 'auto' camera.iso = 600 camera.contrast = 50 rawCapture = PiRGBArray(camera, size=tuple(conf["resolution"])) mp = MusicPlayer() mp.connect() currentUrl = "" server = ServerConnection() # allow the camera to warmup, then initialize the average frame, last # uploaded timestamp, and frame motion counter print("[INFO] warming up...") time.sleep(conf["camera_warmup_time"]) #bg = cv2.imread("query.png") #bg = cv2.cvtColor(bg, cv2.COLOR_BGR2GRAY) #bg = cv2.GaussianBlur(imutils.resize(bg, width=320), (21, 21), 0) bg = None
def __init__(self, configFile: str): self.config = loadConfig(configFile) self.player = MusicPlayer() self.database = MusicDatabase(self.config['database']) self.playlist = Playlist() thread.start_new_thread(self.primaryThread, ())
class PiPlayer: def __init__(self, configFile: str): self.config = loadConfig(configFile) self.player = MusicPlayer() self.database = MusicDatabase(self.config['database']) self.playlist = Playlist() thread.start_new_thread(self.primaryThread, ()) def connect(self, *, initialize: bool = False): self.database.connect(initialize=initialize) def disconnect(self): self.database.disconnect() def playTest(self): pass def scanLibrary(self): def scanDirectory(self, directory: str, recursive: bool = False): for path in listdir(directory): fullPath = join(directory, path) if isdir(fullPath): if recursive: scanDirectory(self, fullPath, recursive) else: try: meta = MusicMetadata() meta.loadFile(fullPath) results = self.database.fetchMusicRowResults( 'file', fullPath) shouldAdd = results is None or results.count < 1 self.database.addMusic(meta, update=not shouldAdd) except: pass for directory in self.config['directories']: directoryPath = abspath(directory['path']) recursive = directory['recursive'] scanDirectory(self, directoryPath, recursive) def primaryThread(self): while (self.playlist.state == PlaylistState.Uninitialized): sleep(1) self.playSong(self.playlist.currentSong()) self.playlist.state = PlaylistState.Playing self.playlist.next() while (self.playlist.state != PlaylistState.End): if (self.player.state == MusicPlayerState.Ended): self.playSong(self.playlist.currentSong()) self.playlist.next() sleep(1) def playSong(self, song: MusicMetadata): self.player.load(song.file) print("Now playing") print(song.title) print("By " + song.artist) print(song.album) self.player.play() def loadPlaylist(self, playlistName: str): try: self.playlist.load(self.database.fetchPlaylist(playlistName)) except: pass
from os import sys from musicplayer import MusicPlayer # Colors BLACK = (0, 0, 0,) WHITE = (255, 255, 255) # START PYGAME pygame.init() # Size [width, height] size = [500, 700] #screen = pygame.display.set_mode(size) #pygame.display.set_caption("Music Control") clock = pygame.time.Clock() pygame.joystick.init() player = MusicPlayer() # BUTTON VALUES Controller = pygame.joystick.Joystick(0) Controller.init() HAT_VAL = 0 MUTE_BUTTON = 3 PAUSE_BUTTON = 0 NEXT_BUTTON = 5 PREV_BUTTON = 4 # CHEX MIX # TODO add pygame printing nogo = True while nogo: joystick_count = pygame.joystick.get_count()
def build(self): return MusicPlayer()
from entity.sun import Sun from util.bus import Bus import mouseListener import painter import actioner from entity.zombie.zombie_head import Zombie_head from entity.zombie.zombie_dead import Zombie_dead from entity.plant.cherryBomb import CherryBomb import threading import time bus = Bus() sets = Setting() screen = pygame.display.set_mode((1400, 600), 0, 0) bus.music = MusicPlayer() bus.music.play() def initSun(): for i in range(1): xx = random.randint(260, 880) yy = -random.randint(100, 300) goal = random.randint(300, 600) sun = Sun(screen, sets.sunImage, xx, yy, goal) bus.sunFall.append(sun) ''' paint部分
#logger.info('Starting the browser') # #options = Options() #options.headless = True #browser = webdriver.Firefox(options=options) browser = None # creating music player logger.info("Making music player") ytdl_format_options = { 'format': 'bestaudio/best', 'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s', 'restrictfilenames': True, 'nocheckcertificate': True, 'ignoreerrors': False, 'logtostderr': False, 'quiet': True, 'no_warnings': True, 'default_search': 'auto', 'source_address': '0.0.0.0' # bind to ipv4 since ipv6 addresses cause issues sometimes } ytdl = youtube_dl.YoutubeDL(ytdl_format_options) ytdl.add_default_info_extractors() mp = MusicPlayer(client, ytdl) # connecting to discord logger.warning('Connecting to discord...') client.run(token)
def restart(bus, screen): # 用于表示是否选择了卡片 bus.cardState = Constant.CARD_NOT_CLICKED # 表示选择卡片的类型 bus.cardSelection = Constant.NUT_SELECTED # 表示当前需要绘制的图片 bus.paintPlants = [] # 僵尸存储列表 bus.zombies = [] # 僵尸频率值 bus.zombieIndex = 0 # 掉头信号 bus.headFlag = True bus.zombieRate = 0 # 存放正在下落太阳的列表 bus.sunFall = [] # 存放已经停止的太阳的列表 bus.sunStay = [] for i in range(1): xx = random.randint(260, 880) yy = -random.randint(100, 300) goal = random.randint(300, 600) sun = Sun(screen, sets.sunImage, xx, yy, goal) bus.sunFall.append(sun) # 记录初始阳光数的 bus.sunScore = 100 # 初始化4个太阳 xx yy 分别记录太阳的x坐标和y坐标 # xx = [] # yy = [] # 全局统一的时间轴 bus.globalTime = 0 # 格子的二维数组 bus.gridList = [([-1] * 5) for i in range(9)] # 游戏状态 bus.state = bus.START # 子弹存储列表 bus.bullets = [] #是否进入中段和末段 bus.midPercentage = False bus.finalPercentage = False # 植物频率值 bus.plantIndex = 0 # 子弹生成频率值 bus.shootIndex = 0 # 游戏结束信号 bus.endFlag = 0 bus.music = MusicPlayer() bus.music.play()
def play_music(self, voice_data): songWasFound = False option = '"play all"' shuffle = "True" mode = "compact" title = "none" artist = "none" genre = "none" response = "" try: import sys sys.path.append(self.UTILS_DIR) from musicplayer import MusicPlayer mp = MusicPlayer() # change the directory to location of batch file to execute os.chdir(self.UTILS_DIR) music_word_found = True if is_match( voice_data, ["music", "songs"]) else False meta_data = voice_data.lower().replace("&", "and").replace( "music", "").replace("songs", "").strip() if meta_data == "": # mode = "compact" alternate_responses = self._get_commands("acknowledge response") response = f"{choice(alternate_responses)} Playing all songs{', shuffled' if shuffle == 'True' else '...'}" songWasFound = True elif meta_data and "by" in meta_data.split(" ") and meta_data.find("by") > 0 and len(meta_data.split()) >= 3: option = '"play by"' by_idx = meta_data.find("by") title = meta_data[:(by_idx - 1)].strip().capitalize() artist = meta_data[(by_idx + 3):].strip().capitalize() if mp.search_song_by(title, artist, title): songWasFound = True artist = f'"{artist}"' genre = title alternate_responses = self._get_commands("acknowledge response") response = f"{choice(alternate_responses)} Playing \"{title}\" by {artist}..." else: response = f"I couldn't find \"{title}\" in your music." elif meta_data: option = '"play by"' title = f'"{meta_data}"' artist = f'"{meta_data}"' genre = f'"{meta_data}"' mp.title = meta_data mp.artist = meta_data mp.genre = meta_data if mp.search_song_by(meta_data, meta_data, meta_data): songWasFound = True alternate_responses = self._get_commands("acknowledge response") response = f"{choice(alternate_responses)} Now playing \"{meta_data.capitalize()}\" {'music...' if music_word_found else '...'}" else: response = f"I couldn't find \"{meta_data.capitalize()}\" in your music." if songWasFound: mp.player_status("close") # batch file to play some music in new window os.system( f'start cmd /k "play_some_music.bat {option} {shuffle} {mode} {title} {artist} {genre}"') # get back to virtual assistant directory os.chdir(self.ASSISTANT_DIR) return response except Exception: self.Log("Play Music Skill Error.")