def endGame(): inputBox.delete(0, 'end') msgLog("===============") msgLog(" GAME OVER ") msgLog("===============") PlaySound(None, SND_FILENAME) PlaySound('audio/GameOver.wav', SND_FILENAME)
def endGame(): global bullets, gameRunning if Windows: PlaySound(None, SND_PURGE) PlaySound("Resources/Death.mp3", SND_ASYNC) gameRunning = False for i in range(len(bullets)-1,-1,-1): screen.delete(bullets[i]) #I HAVE NO IDEA WHY THIS LINE IS NEEDED BUT THE GAME WILL CRASH WITHOUT IT SO DO NOT DELETE IT (IT JUST DRAWS THE PLAYER AGAIN) screen.create_polygon(coords1,coords2,coords3,fill=color) screen.create_text(width/2, (height/2) - 50, text="GAME OVER", fill="white", font=("fixedsys", 45)) screen.create_text(width/2, (height/2)+50, text="Score: " + str(points), fill="white",font="fixedsys 22") screen.create_text(width/2, (height/2)+100, text="Time Survived: " + str(round(currentTime,2)) + " seconds", fill="white",font="fixedsys 22") screen.create_text(width/2, (height/2)+150, text="PRESS \"Q\" TO PLAY AGAIN OR \"ESC\" TO QUIT", fill="white",font="fixedsys 22") #WRITE HIGHSCORE IF IT IS GRATER THAN WHAT IS ALREADY IN THE JSON FILE with open("Resources/Highscores.json","r") as data: obj = load(data) hs = (obj["highScore"]) if points > hs: with open("Resources/Highscores.json","w") as data: obj["highScore"] = points dump(obj, data)
def sound_handler(self): while not self.shutdown: if self.metronome: delay = 60.0 / self.met_bpm s_beep_dur = max(0.3, delay * 0.25) # print(delay,s_beep_dur) ms_beep_dur = s_beep_dur * 1000 if self.met_count == 1: #down beat Beep(1000, int(ms_beep_dur)) else: Beep(700, int(ms_beep_dur)) # print(self.met_count,TIME_SIG) if self.met_count >= TIME_SIG: self.met_count = 1 else: self.met_count += 1 time.sleep(delay - s_beep_dur) if not self.midsong and self.showtime: path = "../music/" + str( TIME_SIG) + "/" #choose music for the set time signature songs = os.listdir(path) song = songs[randint(0, len(songs) - 1)] #randomly select a song name, source, speed = song[:-4].split("_") # print(song, name, source, speed) self.log = "Playing '" + name + "' from '" + source + "' at " + speed + " BPM" PlaySound(path + song, SND_ASYNC | SND_ALIAS) self.midsong = True elif self.midsong and not self.showtime: self.log = "Stopping playback" PlaySound(None, SND_ASYNC | SND_ALIAS) self.midsong = False else: continue
def tick(self): self.set_angle() self.time_string.text = self.time.strftime('%H:%M:%S') self.render() self.canvas.after(1000, self.do_tick) if self.sound: if os.path.isfile("tick.wav"): PlaySound("tick.wav", SND_FILENAME | SND_ASYNC | SND_NODEFAULT) else: Beep(350, 60) if self.alarm and not self.is_alarm: test_angle = int(self.arrow4.angle if self.arrow4.angle >= 0 else self.arrow4.angle + 360) if test_angle == self.arrow3.angle % 360: self.is_alarm = True if self.is_alarm: if os.path.isfile("alarm.wav"): PlaySound("alarm.wav", SND_FILENAME | SND_LOOP | SND_ASYNC | SND_NODEFAULT) else: for i in range(4): Beep(2000, 100)
def sound(on_tap): if on_tap == 'bounce': # os.system("afplay bounce.wav&") # On MAC # os.system("aplay bounce.wav&") # On Linux PlaySound("bounce.wav", SND_ASYNC) # On Windows elif on_tap == 'goal': # os.system("afplay 258020_kodack_arcade-bleep-sound.wav&") # os.system("aplay 258020_kodack_arcade-bleep-sound.wav&") PlaySound("258020__kodack__arcade-bleep-sound.wav", SND_ASYNC) else: # os.system("afplay 391539__mativve__electro-win-sound.wav&") # os.system("aplay 391539__mativve__electro-win-sound.wav&") PlaySound("391539__mativve__electro-win-sound.wav", SND_ASYNC)
def Interrupteur_Musique_MENU(inutile): global Etat_Musique, Allow_Musique """ Meme fonction que Interrupteur_Musique mais qui permet de lancer la musique du Menu lorsqu'on la met sur "on" """ if Etat_Musique == "On": Etat_Musique = "Off" Allow_Musique = False Can.itemconfig(T_Etat_Musique, text=Etat_Musique) PlaySound("Musiques\Vide.wav", 1) else: Etat_Musique = "On" Allow_Musique = True Can.itemconfig(T_Etat_Musique, text=Etat_Musique) PlaySound("Musiques\CreamOnChrome.wav", 1) #Lance une musique
def gameloop(): global isLinkDead global isGameWon #update time global currentTime global isIntroFinished currentTime = time.time() - startTime #check if enemies dead for enemy in currentTile.enemiez: if enemy.hp <= 0: msgLog(f"{enemy.name} {enemy.num} is dead.") currentTile.enemiez.remove(enemy) drop = enemy.drops[random.randint(0, len(enemy.drops) - 1)] if drop and random.random() < 0.5: currentTile.items.append(drop) msgLog(f"{enemy.name} {enemy.num} dropped \"{drop}\".") currentTile.items.sort() #let enemies do actions if not isLinkDead: for enemy in currentTile.enemiez: if currentTime > enemy.nextActionTime: strToLog = enemy.action(link) if strToLog: msgLog(strToLog) if currentTile.pos.x == 2 and currentTile.pos.y == 3 and currentTile.pos.z == 1 and not isGameWon: isGameWon = True winGame() #check for player death if link.hp <= 0 and not isLinkDead: msgLog(f"{link.name} is dead.") isLinkDead = True endGame() if link.stopDodgingTime < currentTime: link.isDodging = False #change the music if (currentTime > 6.798) and not isIntroFinished: isIntroFinished = True if not isLinkDead: PlaySound('audio/OverworldLoop.wav', SND_FILENAME | SND_ASYNC | SND_LOOP) else: PlaySound('audio/GameOverLoop.wav', SND_FILENAME | SND_ASYNC | SND_LOOP) #call this function in 25 ms (so it loops) root.after(25, gameloop)
def set_word_complete(self, word_en, all_complete): for label in self.labelarray_wordlist: if label.cget("text") == word_en: label.configure(font=self.clue_complete_font) self.num_words_found += 1 break if all_complete: PlaySound('wordsearch/wordsearch_complete.wav', SND_FILENAME | SND_ASYNC) WordsearchGameOverWindow(self.root) else: sound_file = str.format('wordsearch/wordsearch_success_{0}.wav', ((self.num_words_found - 1) % 5) + 1) PlaySound(sound_file, SND_FILENAME | SND_ASYNC)
def play(self, sound_name): """Plays a sound based on the entered sound name""" sound_name += '.wav' if sound_name in self.sounds and self.master_instance.sound_enabled: if self.platform == "Windows": PlaySound(path.join('sounds', sound_name), SND_ASYNC)
def script_voiceMessage(self, gesture): if self.recordConfig == "desactivado": gesture.send() return self.focusObj = api.getFocusObject() self.searchList() try: for obj in reversed( api.getForegroundObject().children[1].children): if obj.UIAAutomationId == "btnVoiceMessage": obj.doAction() self.recordObj = obj PlaySound("C:/Windows/Media/Windows Startup.wav", SND_FILENAME | SND_ASYNC) break self.focusObj.setFocus() except: pass try: if self.recordObj.next.UIAAutomationId != "ElapsedLabel": # Translators: Mensaje que indica el comienzo de la grabación message(_('grabando')) elif self.recordObj.next.UIAAutomationId == "ElapsedLabel": # Translators: Mensaje que indica el envío de la grabación message(_('Enviado')) except: pass
def lopetus(self): """ Kun pelaajan pelimerkit loppuvat, toteutetaan tämä funktio. Luo ikkunan johon pelaaja syöttää nimimerkkinsä. Jos pelaajan pisteet ovat tarpeeksi hyvät, pääsee hän TOP-10 listalle. Kehitettävää: kysyy pelaajan nimimerkkiä ainoastaan silloin, kun pelaa- jan pisteet riittävät TOP-10 listalle. Kehitettävää: rajaa pelaajan nimimerkin tietyn pituiseksi """ PlaySound('lopetus.wav', 1) self.__jakonappi = Button(self.__mainwindow, text="Jaa", bg="lightblue", state=DISABLED, command=self.pelaa) self.__jakonappi.grid(row=7, column=5, sticky=W + E + N + S, pady=10) self.__top10ruutu = self.__top10ruutu() self.__top10ruutu.title("Peli päättyi") Label(self.__top10ruutu,text="Syötä nimimerkkisi:")\ .grid(row=0, column=0, columnspan=2, sticky=W+E) self.__top10 = self.__top10(self.__top10ruutu) self.__top10.grid(row=1, column=0, sticky=W + E) self.__top10.bind('<Return>', self.enter) okButton = Button(self.__top10ruutu, text="OK", command=self.lue_syöte) okButton.grid(row=1, column=1)
def main(): buildZones(1, 2) try: env.overwriteOutput = True arcpy.CheckOutExtension("spatial") LayerList = [ "emissions", "fuelcon", "scorchht", "treem" ] ##["crowni","flame","spread","intensity"]##,"emissions","fuelcon","scorchht","soilh","treem"] for MapZone in MapZones: print "MapZone " + MapZone for Layer in LayerList: print "\tWorking on " + Layer # Set layer and path variables # inLayer = MapZone+"_"+Layer # RawDataPath = inDataPath+"\\"+MapZone+"_fh_grids" # outPath = inDataPath+"/outest" # env.workspace= RawDataPath ##################################### # If the layer is crowni, scorchht or treem, then recalculate nonforested pixel FrstMaskList = ["crowni", "scorchht", "treem"] MaskRaster = 'H:/fireharmQAQC/zips/Event_Mode/z01_fh_grids/%s_evc_tree' % ( MapZone) if Layer in FrstMaskList: reclassNonforest(Layer, MaskRaster) else: tmpRaster = Raster(inLayer) global tmpRaster reclass(Layer) ##################################### # Reclassify to High(2)/NotHigh(1) # arcpy.CheckInExtension("spatial") # ** RUN TIME STATS ***********************************************************# timeStats() #******************************************************************************# except: # get the traceback object tb = sys.exc_info()[2] # tbinfo contains the line number that the code failed on and the code from that line tbinfo = traceback.format_tb(tb)[0] # concatenate information together concerning the error into a message string seperator = "********************************************************************************" pymsg = "PYTHON ERRORS:\nTraceback Info:\n" + tbinfo + "\nError Info:\n " + str( sys.exc_type) + ": " + str(sys.exc_value) # generate a message string for any ArcGIS tool errors msgs = seperator + "\nArcGIS ERRORS:\n" + arcpy.GetMessages(2) # return ArcGIS messages for use with a script tool arcpy.AddError(msgs) arcpy.AddError(pymsg) # print messages for use in Python/PythonWin print msgs print pymsg print "\nSCRIPT FAILED..." #Play wav file to let me know it has failed! file = 'Windows XP Error.wav' from winsound import PlaySound, SND_FILENAME, SND_ASYNC PlaySound(file, SND_FILENAME | SND_ASYNC)
def nugumu_speak(text): os.makedirs("tmp", exist_ok=True) voice = wincl.Dispatch("SAPI.SpVoice") savefile = wincl.Dispatch("SAPI.SpFileStream") voice.Rate = -6 pitch = -10 sentence = f'<pitch absmiddle=\"{pitch}\">{text}</pitch>' savefile.Open("tmp/normal.wav", 3) voice.AudioOutputStream = savefile voice.Speak(sentence) savefile.Close() change_rate = 0.8 with wave.open("tmp/normal.wav", "rb") as voicefile: rate = voicefile.getframerate() signal = voicefile.readframes(-1) with wave.open("tmp/adjusted.wav", "wb") as adjusted_voicefile: adjusted_voicefile.setnchannels(1) adjusted_voicefile.setsampwidth(2) adjusted_voicefile.setframerate(rate * change_rate) adjusted_voicefile.writeframes(signal) with open("tmp/adjusted.wav", "rb") as f: data = f.read() PlaySound(data, SND_MEMORY)
def Retour_MENU(inutile): global Allow_Musique """ Fonction qui permet de revenir au menu """ if Allow_Musique == True: PlaySound("Musiques\CreamOnChrome.wav", 1) MENU("inutile")
def much(character): if character != 'beach1': musicfile = character.room['music'] else: musicfile = 'ocean.wav' if os.path.isfile(musicfile): PlaySound(musicfile, winsound.SND_ASYNC | winsound.SND_LOOP)
def get_loot(self, opening_window): self.open_button['state'] = tk.NORMAL opening_window.destroy() #destroy the "please wait" window lootwindow = tk.Toplevel() lootwindow.geometry('600x400') lootlb = tk.Label(lootwindow, text='Congratulations! You got...', width=20, height=3, font='arial 14') lootlb.pack(side='top') loot = self.inventory.generate_loot() tier, item, price = loot[0], loot[1], loot[2] self.inventory.add_to_inventory(item, price) #loot text loot = tk.Label(lootwindow, text=item, width=35, height=2, fg=quality_colors.get(tier), font='arial 19') #quality text qual = tk.Label(lootwindow, text=tier.upper() + ' Quality!', fg=quality_colors.get(tier), width=20, height=2, font='arial 22') loot.place(rely=0.9, relx=0.5, anchor=tk.CENTER) qual.place(rely=0.5, relx=0.5, anchor=tk.CENTER) PlaySound('l.wav', SND_FILENAME)
def play(path): frame, start = 0, time() f = open(path, mode="r") data = f.readline() fps, music = float(data[:data.find("|")]), data[data.find("|") + 1:data.find("\n")] print(fps) if music: try: PlaySound(music, SND_FILENAME | SND_ASYNC) except Exception as e: print(e) try: while data: data = "" while not "XXX" in data: data += f.readline() print(data[:data.find("XXX") - 1], end="", flush=True) wait(start, fps, frame) frame += 1 data = f.readline() except KeyboardInterrupt: pass print("Bye")
def play_file(filename: str) -> int: """Outputs console error code, if any, as int""" from os import name as os_name if os_name == 'nt': # Windows NT from winsound import PlaySound, SND_FILENAME PlaySound(filename, SND_FILENAME) return 0 if os_name == 'posix': # Linux OR Mac... probably from os import system from platform import system as get_os_name if get_os_name() == 'Linux': return system(f'aplay {filename}') if get_os_name() == 'Darwin': # Mac return system(f'afplay {filename}') if get_os_name() == 'Haiku': return system(f'media_client play {filename}') if get_os_name()[-3:] == 'BSD': for command in 'vlc aplay cmus moc mpv mplayer mplayer2'.split(): if not system(f'{command} {filename}'): return 0 else: return 32512 elif os_name == 'os2': return system(f'fmgplay {filename}') # unknown OS, try to use pygame import pygame # unfortunately no 32-bit support # play audio file with pygame pygame.mixer.init() pygame.mixer.music.load(filename) pygame.mixer.music.play() pygame.quit() return 0
def handleEvent(self, event): print "state is: %s" % (self.state) if self.state == "START": if event == "NIGHT_START": self.state = "ACQUIRING_DEEP_SLEEP" if event == "SLEEP_ONSET": self.state = "ACQUIRING_DEEP_SLEEP" elif self.state == "ACQUIRING_DEEP_SLEEP": if event == "DEEP_SLEEP_DONE": self.state = "WAIT_FOR_REM_TRANSITION" elif self.state == "WAIT_FOR_REM_TRANSITION": if event == "REM_TRANSITION": self.state = "ALARMING" print "ALARM!!!" file = '78562_joedeshon_alarm_clock_ringing_01.wav' if platform.system().lower().find('win') > -1: from winsound import PlaySound, SND_FILENAME, SND_ASYNC PlaySound(file, SND_FILENAME | SND_ASYNC) elif platform.system().lower().find('linux') > -1: print "TODO: can't figure out how to play audio in Linux without Mplayer installed yet!" print "Press 'Q' or 'ESC' to stop the alarm" try: subprocess.call(['mplayer -msglevel all=-1 ' + file], shell=True) except OSError, e: print >> sys.stderr, "Execution failed:", e else: print "TODO: unsupported OS: %s" % (platform.system())
def script_previousElement(self, gesture): fc = api.getFocusObject() if fc.role != controlTypes.ROLE_TAB: manager.emulateGesture(KeyboardInputGesture.fromName("shift+tab")) else: PlaySound("C:/Windows/Media/Windows Information Bar.wav", SND_ASYNC | SND_FILENAME)
def check_signal(self, rule_name: str, rule_value: float) -> None: """""" signals = self.rule_signal_map[rule_name] if not signals: return for signal in list(signals): triggered = False if signal.signal_type == SignalType.GREATER_THAN: if rule_value > signal.signal_target: triggered = True elif signal.signal_type == SignalType.LESS_THAN: if rule_value < signal.signal_target: triggered = True elif signal.signal_type == SignalType.EQUAL_TO: if rule_value == signal.signal_target: triggered = True if triggered: signal.active = False signals.remove(signal) self.put_event(EVENT_RADAR_SIGNAL, signal) msg = (f"雷达信号{signal.signal_id}已触发," f"规则{signal.rule_name}实时计算数值{rule_value}," f"{signal.signal_type.value}目标{signal.signal_target}") self.write_log(msg) if signal.signal_email: self.main_engine.send_email("市场雷达", msg) if signal.signal_sound and PlaySound: PlaySound("SystemHand", SND_ASYNC)
def initOpenGl(drawParameter, onMouseKey, onKeyboardKey, onSpecialKey): global currentTime global draw glutInit() glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH) glutInitWindowSize(500, 500) glutCreateWindow(b"EAT.io") # pygame.mixer.init(44100, -16, 2, 2048) # intianliazion of game sound # pygame.mixer.music.load("/resources/sounds/bg_music.wav") # open sound file # pygame.mixer.music.play(-1) # play sound to infint PlaySound("resources/sounds/bg_music.wav", SND_FILENAME | SND_LOOP | SND_ASYNC) currentTime = time() draw = drawParameter glutDisplayFunc(displayFunction) glutIdleFunc(displayFunction) glutMouseFunc(onMouseKey) glutKeyboardFunc(onKeyboardKey) glutSpecialFunc(onSpecialKey) glutMainLoop()
def _play(soundfile): if platform.startswith('win'): from winsound import PlaySound, SND_FILENAME, SND_ASYNC PlaySound(soundfile, SND_FILENAME|SND_ASYNC) elif 'linux' in platform: from wave import open as waveOpen from ossaudiodev import open as ossOpen s = waveOpen(soundfile,'rb') (nc,sw,fr,nf,comptype, compname) = s.getparams( ) try: from ossaudiodev import AFMT_S16_NE except ImportError: if byteorder == "little": AFMT_S16_NE = ossaudiodev.AFMT_S16_LE else: AFMT_S16_NE = ossaudiodev.AFMT_S16_BE dsp = None try: dsp = ossOpen('/dev/dsp','w') dsp.setparameters(AFMT_S16_NE, nc, fr) data = s.readframes(nf) s.close() dsp.write(data) except IOError: print _("Audio device is busy.") finally: if dsp: dsp.close()
def intro_music(): file = [ 'C:\\Users\evans\OneDrive\Documents\CIS440_Game_music\Pusha T - If You Know You Know.wav' ] #for f in file: song = random.choice(file) PlaySound(song, SND_FILENAME | SND_LOOP | SND_ASYNC)
def play_sound(sf: str): if pathlib.Path(sf).exists(): try: from winsound import PlaySound, SND_FILENAME except ImportError: pass else: PlaySound(sf, SND_FILENAME)
def end(self, sound=False): run_time = time() - self._start print("Timestamp end: %s, %.2fs" % (ctime(), run_time)) try: if sound: PlaySound('SystemQuestion', SND_ALIAS) except RuntimeError: print('RuntimeError: Faild to play sound!')
def __init__(self, master): frame = Frame(master) frame.pack() self.button = Button(frame, text='play music', command=self.play_sound,bg="blue", fg="white") self.button.pack(side=RIGHT) self.button2 = Button(frame, text='stop music', command=self.stop_sound,bg="blue", fg="white") self.button2.pack(side=RIGHT) PlaySound('sound.wav', SND_FILENAME | SND_LOOP | SND_ASYNC)
def max_panos(self): """ Muuttaa pelaajan panoksen pelimerkkien suuruiseksi. """ PlaySound('max_panos.wav', 1) self.__panosMAX += 1 self.__mpanos.set("Panos: {}".format( self.muuta_lukuasua(self.__pelimerkit)))
def runGame(): global end, points,spawnChance,gameRunning, player, pos1,loop if Windows: PlaySound(None, SND_PURGE) PlaySound("Resources/Splash.mp3", SND_ASYNC + SND_LOOP) loop = False screen.delete("all") screen.update() setInitialValues(color) drawObjects() scoreshiper = time() gameRunning = True while True: if randint(1, spawnChance) == 1: if randint(1,2) == 1: drawasteroidR() else: drawasteroidL() if gameRunning == True: moveasteroids() movePlayer() spawnBullet() moveBullets() checkEdges() clean() points += collision() updateScore(points) if (time() - scoreshiper) > 1: points += 10 updateScore(points) scoreshiper = time() updateTime() screen.update() sleep(0.01) screen.delete(player) endGame()
def speak(text, filename): engine = pyttsx3.init('sapi5') voices = engine.getProperty("voices")[0] engine.setProperty('voice', voices) engine.save_to_file(text, f"{filename}.mp3") engine.runAndWait() PlaySound(f"{filename}.mp3", True) print("File has been converted to {}.mp3. Now playing the file".format(filename)) input("Hit enter to Complete!!!")