def run(self, settings_filename): with open(settings_filename, 'r') as settings_file: sound_features = json.load(settings_file) sounds = [] for sound_filename in sound_features: snd = sound.Sound(sound_filename) features = sound_features[sound_filename] print('Analyzing {}'.format(snd.filename)) self.analyzer.analyze_multiple([snd], features) if not snd.is_silent: std = standardizer.Standardizer([snd]) std.calculate_feature_statistics() std.add_standardized_series() snd.analysis['series'] = snd.analysis['series_standardized'] del snd.analysis['series_standardized'] std.round_to_precision(self.precision) sounds.append(snd) json_data = {snd.filename: snd.analysis['series'] for snd in sounds} json_data_serialized = json.dumps(json_data, separators=(',', ':')) template = Template('window.audioAnalysis={{ json_data }};') js = template.render(json_data=json_data_serialized) with open(os.path.join(settings.INPUT_DIRECTORY, 'audioAnalysis.js'), 'w') as outfile: outfile.write(js)
def __init__(self): self.camera = camera.Camera() self.track = track.Track() self.track.generateTrack(20, 50) self.sound = sound.Sound() #self.camera.position = (self.track.startingPoint[0], 1, self.track.startingPoint[1]) self.rotation = 0 self.unicycles = [] self.unicycles.append( racer.Racer( array([ self.track.startingPoint[0], 0.3, self.track.startingPoint[1] ]), self.track.startingRot, 75, 4, self.track, self.sound)) tilted = racer.Racer(array([-2, 0.3, 2]), 0) tilted.orientation = array([1, 1, 0]) self.unicycles.append(tilted) tilted2 = racer.Racer(array([2, 0.3, -2]), 0) tilted2.orientation = array([0, 1, 1]) self.unicycles.append(tilted2) tilted3 = racer.Racer(array([-2, 0.3, -2]), 0) tilted3.orientation = array([1, 1, 1]) self.unicycles.append(tilted3) self.currentTime = pygame.time.get_ticks() self.accumulator = 0
def __init__(self): self.__point = 0 self.__blocks = numpy.zeros((Box.WIDTH * Box.HEIGHT)).reshape(Box.HEIGHT, Box.WIDTH) self.__gen = TetriminoGenerator() self.__mino = self.__gen.generate() self.__estimate_y = 0 self.__point = 0 self.__sound = sound.Sound()
def __init__(self, x, y, r, color): self.mX = x self.mY = y self.mR = r self.mColor = color self.mDy = 0 self.mGravity = 2 self.mSound = sound.Sound("bounce_sound.wav") return
def __init__(self, name, scene_handler=None, ui=None, load_path=None, clip=True): super(Scene, self).__init__() self.name = name self.handler = scene_handler self.batch = pyglet.graphics.Batch() self.fresh = (load_path is None) if clip: self.main_group = ClipGroup(w=gamestate.main_window.width, h=gamestate.main_window.height) else: self.main_group = None self.ui = ui self.actors = {} self.camera_points = {} self.interaction_enabled = True self.blackout = False self.game_time = 0.0 self.accum_time = 0.0 self.clock = pyglet.clock.Clock(time_function=lambda: self.game_time) self.paused = False self.x_offset = 0.0 self.y_offset = 0.0 self.sound_player = sound.Sound() self.shadow = shadow.ShadowManager() self.moving_camera = False self.resource_path = util.respath_func_with_base_path( 'game', self.name) self.init_clock() self.init_zenforcer() self.interp = interpolator.InterpolatorController() self.convo = convo.Conversation(self) self.background_convos = set() self.init_convenience_bindings() self.load_info(load_path) self.initialize_from_info() self.load_actors() self.zenforcer.init_groups() if gamestate.scripts_enabled: self.load_script() for i in xrange(10): self.zenforcer.update() self.update(0)
def genre_stat(filename): song = sound.Sound(filename) song.load_and_gen_obj() stats = make_stats(song) prediction = recognizer.recognize('song.mp3') genre = index_to_genre(prediction) return jsonify({ 'genre': genre, 'duration': song.duration, 'tempo': song.tempo[0], 'tuning': song.tuning }), 200
def invert_noisy_subbands(target_envs, final_sr, env_sr, mid_sr=20000, low_lim=20, hi_lim=10000, comp_exp=0.3, scale_volume=2.): # number of subbands (w/o high/low pass) nbands = target_envs.shape[1] - 2 snd_len = int(np.ceil(target_envs.shape[0] * float(mid_sr) / float(env_sr))) snd_len -= (snd_len % 100) target_envs = np.clip(target_envs, 0, 1) filts, _, _ = erb_filters(snd_len, mid_sr, nbands, low_lim, hi_lim) synth_sound = np.random.randn(snd_len) if 0: print('using pink noise') noise_snd = sound.load_sound( '/data/vision/billf/aho-stuff/vis/lib/soundtex/pink_noise_20s_20kHz.wav' ) noise_snd = noise_snd.normalized().to_mono() noise_snd = noise_snd.samples i = np.random.choice( list(range(noise_snd.shape[0] - synth_sound.shape[0]))) synth_sound = 100 * noise_snd[i:i + synth_sound.shape[0]] print('stdev', np.std(synth_sound)) #sound.play(synth_sound, mid_sr) # Forward pass: current sound -> downsampled envelopes and full-res phases synth_subbands = subbands_from_sound(synth_sound, filts) analytic = scipy.signal.hilbert(synth_subbands, axis=0) synth_envs = np.abs(analytic) #phases = analytic / synth_envs phases = analytic #up_target_envs = resample(target_envs, mid_sr / env_sr) up_target_envs = scipy.signal.resample(target_envs, phases.shape[0]) up_target_envs = np.maximum(up_target_envs, 0.) up_target_envs **= (1. / comp_exp) new_analytic = phases * up_target_envs synth_subbands = np.real(new_analytic) synth_sound = sound_from_subbands(synth_subbands, filts) synth_sound = resample(synth_sound, final_sr / float(mid_sr)) synth_sound = synth_sound * scale_volume synth_sound = np.clip(synth_sound, -1., 1.) return sound.Sound(None, final_sr, synth_sound)
def init(self): pygame.init() pygame.display.set_caption(constant.WINDOW_NAME) self._display_surf = pygame.display.set_mode( (constant.WINDOW_WIDTH, constant.WINDOW_HEIGHT)) self._running = True self._except_new_game = False self._background = pygame.image.load( constant.FILE_BACKGROUND).convert() self._logic = logic.Logic() self._logic.start() self._sound = sound.Sound() self._sound.play() self._font = pygame.font.SysFont("Arial", 20) self._end_font = pygame.font.SysFont("Arial", 30)
def __init__(self): """ Constructor for Tab class """ session = HTMLSession() r = session.get(url) r.html.render() text = r.html.text start_index = text.find('Download\nPlay\n') + 14 final_index = text[start_index:].find(end) + start_index self.tab = text[start_index:final_index] self.e_is_lowercase = True self.strings = self._find_strings() self.blocks = [] self._strip3() s = sound.Sound(self.blocks) tstring = self.tab_string()
def loadEnvFile(self, envFileName, debugInfo=False): if(debugInfo): print envLoader.getFilesList(envFileName) for sFile in envLoader.getFilesList(envFileName): thisFilePath = sFile[0] ## where is the file located in this PCs file tree decVolume = float(sFile[1]/100.0) ## volume is stored in the file as a value from 0 to 100, so we ## adjust it to be correct for a scale from 0.0 to 1.0 thisFilesType = sFile[2] ## what type of file is this in ['background', 'short', 'music'] loadedSoundObject = sound.Sound('./data/%s' % thisFilePath, decVolume, thisFilesType) self.audioFiles[thisFilePath] = loadedSoundObject
def reencode_subbands(snd, nbands, env_sr, matlab_encode=False, matlab_decode=False, do_decode=True): if matlab_encode: envs = soundrep.matlab_subband(snd, env_sr) else: envs = subband_envs(snd, nbands, env_sr) if do_decode: ut.toplevel_locals() if matlab_decode: return sound.Sound( None, snd.rate, soundrep.matlab_inv_subband(envs, snd.rate, env_sr, nbands=nbands)) return invert_subband_envs(envs, snd.rate, env_sr)
def invert_subband_envs(target_envs, final_sr, env_sr, mid_sr=20000, niters=3, low_lim=20, hi_lim=10000, comp_exp=0.3): # number of subbands (w/o high/low pass) nbands = target_envs.shape[1] - 2 snd_len = int(np.ceil(target_envs.shape[0] * float(mid_sr) / float(env_sr))) snd_len -= (snd_len % 100) target_envs = np.clip(target_envs, 0, 1) #snd_len = good_resample_length(target_envs.shape[0], mid_sr, env_sr, 10) filts, _, _ = erb_filters(snd_len, mid_sr, nbands, low_lim, hi_lim) # cut_signal(signal, new_sr, old_sr): synth_sound = np.random.randn(snd_len) for i in range(niters): # Forward pass: current sound -> downsampled envelopes and full-res phases synth_subbands = subbands_from_sound(synth_sound, filts) analytic = scipy.signal.hilbert(synth_subbands, axis=0) synth_envs = np.abs(analytic) phases = analytic / synth_envs #up_target_envs = resample(target_envs, mid_sr / env_sr) up_target_envs = scipy.signal.resample(target_envs, phases.shape[0]) up_target_envs = np.maximum(up_target_envs, 0.) up_target_envs **= (1. / comp_exp) new_analytic = phases * up_target_envs synth_subbands = np.real(new_analytic) synth_sound = sound_from_subbands(synth_subbands, filts) synth_sound = resample(synth_sound, final_sr / float(mid_sr)) synth_sound = np.clip(synth_sound, -1., 1.) return sound.Sound(None, final_sr, synth_sound)
import wx import time import random import model import view import sound TICK = 50 MOVE = 750 / TICK SHIFT = 250 / TICK ENGINE = 100 / TICK TOGGLE = 500 / TICK SOUNDS = [ sound.Sound('./sounds/fever.mp3'), #sound.Sound('./sounds/chill.mp3'), ] class Controller(object): def __init__(self, players): self.players = players self._counter = 0 self._delay = 0 self._sound = random.choice(SOUNDS) frame = view.MainFrame() for player in players: player._offset = 0 frame.add_player(player) frame.Bind(wx.EVT_CHAR, self.on_char) frame.Centre()
def __init__(self): # базовые размеры экрана, бара и "моря" self.SCREEN_RECT = pygame.Rect((0, 0), (1024, 768)) self.BAR_RECT = pygame.Rect((0, 0), (self.SCREEN_RECT.w, 60)) self.SEA_RECT = pygame.Rect( (0, self.BAR_RECT.h), (self.SCREEN_RECT.w, self.SCREEN_RECT.h - self.BAR_RECT.h)) # инициализация pygame pygame.init() # устанавливаем заголовок pygame.display.set_caption("Весёлая рыбалка") # создаем окно self.screen = pygame.display.set_mode( (self.SCREEN_RECT.w, self.SCREEN_RECT.h), HWSURFACE | DOUBLEBUF) # массив рыб self.fishes = [] # заполняем список файлов рыб data_dir = os.listdir("data") # выбираем только файлы рыб self.fish_pics = re.findall("fish\d\d.png", ''.join(data_dir)) if len(self.fish_pics) == 0: print("Error! Fish pics not found!") sys.exit(255) # создаём колоду self.deck = deck.Deck() # создаем верхний бар self.u_bar = ubar.UBar(self.screen, self.BAR_RECT, self.deck) self.u_bar.draw() # загружаем звуки self.games_sounds = sound.Sound() # включаем музыку self.games_sounds.play_music() # буква за которой охотимся self.big_char = self.u_bar.get_curchar() # создаем море self.Sea = sea.Sea(self.screen, self.SEA_RECT) # создаем крючок и леску self.FishHook = hook.FishHook(self.screen, self.SEA_RECT) # таймер self.clock = pygame.time.Clock() # инициализируем джойстик, если есть if pygame.joystick.get_count() > 0: joy = pygame.joystick.Joystick(0) joy.init() # заполняем массив рыбами передавая путь до файлов for i in range(3): self.fishes.append( fish.Fish(self.screen, self.SEA_RECT, os.path.join("data", random.choice(self.fish_pics)), self.big_char, self.u_bar, self.deck))
def __init__(self): # Avoid reinitialisation in case of multiple call # Theorically impossible due to the Singleton decorator if hasattr(self, '_init_complete') and self._init_complete: return # Camera Configuration # Splitter ports are for : # 0 - Capture full size images (default resolution) # 1 - Recording full size video (without opencv processing drawn) # 2 - Image processing for the first resolution # 3 - Image processing for the second resolution resolutions = Config().get('camera_resolutions', { 'LD': (160, 120), 'SD': (320, 240), 'default': (1024, 768) }) self.camera = camera.Camera(resolutions['default'], Config().get('camera_framerate', 30)) self.streamers = {} definitions = [r for r in resolutions.keys() if r <> 'default'] for i, definition in enumerate(definitions, start=2): self.streamers[definition] = self.camera.getGrabber( threads=4, size=resolutions[definition], port=i) # Camera's Sensors Configuration self.sensors = {} for sensor, klass in camera_sensors.sensors.iteritems(): self.sensors[sensor] = klass(self.streamers['LD'], draw=self.streamers['SD']) self.sensors['color'].setColor((51, 153, 153)) self.sensors['color'].setColor((162, 161, 105)) #self.sensors['light']._start() self.sensors['fps']._start() # Motors Configuration if Config().get('use_servos', True): if Config().get('use_camera_assisted_moves', True): self.motors = movements.ServosMotionControlled( self.sensors['flow'], Config().get('pin_servo_left', 25), Config().get('pin_servo_right', 4), Config().get('camera_assisted_sensibility', 0.5)) else: self.motors = movements.ServosControl( Config().get('pin_servo_left', 25), Config().get('pin_servo_right', 4)) else: if Config().get('use_camera_assisted_moves', True): self.motors = movements.MotorsMotionControlled( self.sensors['flow'], Config().get('pin_enable_motor', 22), Config().get('pin_motor_left_forward', 25), Config().get('pin_motor_left_backward', 24), Config().get('pin_motor_right_forward', 4), Config().get('pin_motor_right_backward', 17), Config().get('camera_assisted_sensibility', 0.5)) else: self.motors = movements.MotorsControl( Config().get('pin_enable_motor', 22), Config().get('pin_motor_left_forward', 25), Config().get('pin_motor_left_backward', 24), Config().get('pin_motor_right_forward', 4), Config().get('pin_motor_right_backward', 17)) self.motors.freq(Config().get('PWM_frequency', 100)) # Sound Configuration self.sound = sound.Sound() if Config().get('useMbrola', False): self.sound.useMbrola() # Initialisation of superclass is complete self._init_complete = True
import sound import time import audiostream s = sound.Sound() s.add_sound(2, audiostream.WaveAudioStream("test.wav", 0.5)) s.start_streams() time.sleep(2) s.add_sound(2, audiostream.WaveAudioStream("bering.wav", 2)) s.add_sound(2, audiostream.FeedAudioStream(keep_open=True)) time.sleep(10) s.stop_streams() s.terminate()
def init(): lights.meteor() anthem = sound.Sound(join(dirname(__file__), 'sounds', 'uefa-anthem.wav')) anthem.play().wait_done() lights.yellow()
def mapp(n, start1, stop1, start2, stop2): return ((n - start1) / (stop1 - start1)) * (stop2 - start2) + start2 def print_how_to_use(): print( "How to use:\nmove mouse up and down to change frequency,\nclick to add a note with that frequency,\nright click to remove a note,\npress the s key to save,\npress space bar to play,\npress d to delete all notes,\npress c to see controls" ) print("\n\n\n\n") print_how_to_use() audio = sound.Sound() notes = [] note_color = () bg_color = [] done = False x = 10 w = 10 custom = input("do you want to customize note color(y/n): ") if custom == "y": r = int(input("r: ")) g = int(input("g: ")) b = int(input("b: ")) note_color = (r, g, b) elif custom == "n":
def __init__(self): self.sound = sound.Sound() self.arduCon = arduCon.Ardu() self.badgeWasThere = False self.members = data.Members("data.csv") self.g = Tk() self.g.title("FiS - RFID Badge Controller") self.g.minsize(width=800, height=400) cols = 4 self.count = 0 Label(self.g, pady=20, padx=20, font=("Arial", 22), text="FiS - RFID Badge Controller").grid(row=0, columnspan=cols) self.resultLabel = Label(self.g, pady=15, font=("Arial", 16), text="Person: ") self.resultLabel.grid(row=1, columnspan=cols) Label(self.g, pady=30, font=("Arial", 16), text="Server: ").grid(row=2, columnspan=cols) Button(self.g, text="Pull data", command=self.pullData).grid(row=3, column=1, sticky=E) Button(self.g, text="Push data", command=self.pushData).grid(row=3, column=2, sticky=W) Label(self.g, pady=30, font=("Arial", 16), text="Write tag: ").grid(row=4, columnspan=cols) self.nameStr = StringVar() self.nameStr.trace("w", self.updateList) Label(self.g, pady=0, font=("Arial", 14), text="Filter surname: ").grid(row=5, column=1, sticky=E) Entry(self.g, width=20, textvariable=self.nameStr).grid(row=5, column=2, sticky=W) self.forenameStr = StringVar() self.forenameStr.trace("w", self.updateList) Label(self.g, pady=10, font=("Arial", 14), text="Filter forename: ").grid(row=6, column=1, sticky=E) Entry(self.g, width=20, textvariable=self.forenameStr).grid(row=6, column=2, sticky=W) self.dataList = Listbox(self.g, width=80) self.dataList.grid(row=8, columnspan=cols, padx=20) self.showRegistered = BooleanVar() self.showRegistered.set(False) self.showRegistered.trace("w", self.updateList) Checkbutton(self.g, text="Show registered", variable=self.showRegistered).grid(row=9, column=0, sticky=E) self.addBtn = Button(self.g, text="Write to badge", command=self.addBtnAction, state="disabled") self.addBtn.grid(row=9, column=1, sticky=W) self.countlabel = Label(self.g, text="count: " + str(self.count), pady=5, padx=5) self.countlabel.grid(row=9, column=2) self.connectedLabel = Label(self.g, text="connected", bg="red", pady=5, padx=5) self.connectedLabel.grid(row=9, column=3) for i in range(cols): self.g.grid_columnconfigure(i, weight=1) self.g.grid_columnconfigure(i, weight=1) self.g.grid_columnconfigure(i, weight=1) self.g.grid_columnconfigure(i, weight=1) self.g.protocol('WM_DELETE_WINDOW', lambda: self.onClose()) self.updateList() self.showResult() self.guiLoop()
import sound import ??? as myfile # ??? should be replaced with the name of #the file which has your functions. #Read the statements and comments below. #You will need to make appropriate changes to the statements #to work with different wav files and test various functions #you have written. #Converts the sound in grace.wav file to a Sound object. snd = sound.Sound(filename='grace.wav') #The function fade that you have written is called #and the Sound object it returns is assigned to gracefade. gracefade = myfile.fade(snd, len(snd)) #The Sound object gracefade is converted to sound in #a wav file called grace_fade.wav. #This wav file did not exist before but is newly created. gracefade.save_as('grace_fade.wav')
def update(self, delta_time): if self.state == GameState.PLAYING: """ Movement and game logic """ self.boss_timer += 1 self.enemy_timer += 1 for boss in self.boss_list: boss.chase(self.player) ## create new zombies if they are less than a certain amount # if len(self.enemy_list) < 5: # self.timer += 1 # if self.timer > 80: # self.timer = 0 # self.createZombie() self.physics_engine.update() self.player_list.update_animation() # self.enemy_list.update_animation() # self.enemy_list.update() # self.boss_list.update_animation() # self.boss_list.update() # self.bullet_list.update() # self.bullet_list.update_animation() self.explosion_list.update() # self.coin_list.update_animation() # self.coin_list.update() # self.power_up_list.update() # self.power_up_list.update_animation() self.animated_list.update() self.animated_list.update_animation() if self.player.center_x < 20: self.player.center_x = 930 elif self.player.center_x > 940: self.player.center_x = 30 # initialize the shape element list to clear items self.hp_bar_list = arcade.ShapeElementList() # keep zombies in platforms with the help of invisible walls for enemy in self.enemy_list: self.hp_bar_list.append(enemy.rect) # self.hp_bar_list.append(enemy.rect_outline) hit_list = arcade.check_for_collision_with_list( enemy, self.invisible_wall_list) if enemy.left < 20 or enemy.right > 940: enemy.changeDir() if len(hit_list) > 0: enemy.changeDir() ## create boss hp bar for boss in self.boss_list: self.hp_bar_list.append(boss.rect) ## check if bullets hit enemies for bullet in self.bullet_list: if bullet.center_x < 0 or bullet.center_x > 960: bullet.kill() hit_list = arcade.check_for_collision_with_list( bullet, self.enemy_list) if len(hit_list) > 0: self.score += 1 bullet.kill() hp = hit_list[0].getDamage(self.player.dmg) # if zombie hp is 0, kill it and play a sound if hp <= 0: zombie_dying = DeadZombie() zombie_dying.center_x = hit_list[0].center_x zombie_dying.center_y = hit_list[0].center_y + 20 self.explosion_list.append(zombie_dying) zombie_death_sound = sound.Sound(ZOMBIE_DEATH_SOUND) zombie_death_sound.play() ## create a collectible coin new_coin = Coin() new_coin.center_x = hit_list[0].center_x new_coin.center_y = hit_list[0].center_y self.coin_list.append(new_coin) self.animated_list.append(new_coin) for enemy in hit_list: enemy.kill() ## kill zombie corpses after their animation ends for item in self.explosion_list: if item.countdown_timer <= 0: item.kill() ## boss only takes damage when other enemies are cleared for bullet in self.bullet_list: hit_list = arcade.check_for_collision_with_list( bullet, self.boss_list) if len(hit_list) > 0: if (len(self.enemy_list) == 0): self.boss_list[0].getDamage(self.player.dmg) bullet.kill() ## check if player killed the boss if len(self.boss_list ) == 0 and self.temp_state != GameState.MISSION_COMPLETE: mission_complete_sound = sound.Sound(MISSION_COMPLETE) mission_complete_sound.play() self.temp_state = GameState.MISSION_COMPLETE ## release the fire power up which makes player's bullets stronger to kill the boss ## this is release when enemies are cleared if len(self.enemy_list) == 0 and not self.fire_power_up_is_on: self.fire_power_up_is_on = True self.createPowerUp() ## player picks up power up if self.fire_power_up_is_on: hit_list = arcade.check_for_collision_with_list( self.player, self.power_up_list) if len(hit_list) > 0: self.shooting_fire = True power_up_sound = sound.Sound(POWER_UP) power_up_sound.play() self.player.dmg *= 5 self.power_up_list[0].kill() ## if boss or zombies touch the player, game is over boss_hit = arcade.check_for_collision_with_list( self.player, self.boss_list) enemy_hit = arcade.check_for_collision_with_list( self.player, self.enemy_list) if len(boss_hit) > 0 or len(enemy_hit) > 0: distance = 500 if len(boss_hit) > 0: distance = self.player.center_x - boss_hit[0].center_x if len(enemy_hit) > 0: distance = self.player.center_x - enemy_hit[0].center_x ## add some buffer for collisions. 30 seems good if abs(distance) < 30: if self.temp_state != GameState.GAME_ENDING: dead_knight = DeadKnight() dead_knight.center_x = self.player.center_x dead_knight.center_y = self.player.center_y self.temp_state = GameState.GAME_ENDING self.dead_knight_list.append(dead_knight) game_over_sound = sound.Sound(GAME_OVER_SOUND) game_over_sound.play() self.player.kill() ## check if player hits a coin coin_collect_list = arcade.check_for_collision_with_list( self.player, self.coin_list) if len(coin_collect_list) > 0: self.gold += 1 collect_sound = sound.Sound(COIN_COLLECT) collect_sound.play() coin_collect_list[0].kill() if self.gold % 5 == 0: self.player.dmg += 10 ## check if spears hit walls if (len(self.bullet_list) > 0): hit_list = arcade.check_for_collision_with_list( self.bullet_list[0], self.wall_list) if len(hit_list) > 0: self.bullet_list[0].kill() ## if game time is up, increase boss power and play a sound if self.boss_timer / 60 == 10 and len(self.boss_list) > 0: self.boss_list[0].scale *= 1.3 self.boss_list[0].increaseSpeed(1.2) self.boss_list[0].total_hp *= 2 grawl = sound.Sound(MONSTER_GRAWL) grawl.play() self.boss_timer = 0 ## if game time is up, increase zombie power and play a sound if self.enemy_timer / 60 == 15 and len(self.enemy_list) > 0: for enemy in self.enemy_list: enemy.scale *= 1.2 enemy.increaseSpeed(1.2) enemy.total_hp *= 2 grawl = sound.Sound(ZOMBIE_LEVEL_UP) grawl.play() self.enemy_timer = 0
def on_key_press(self, key, modifiers): """ Called whenever a key is pressed. """ if key == arcade.key.P: time.sleep(10) if key == arcade.key.ENTER: if self.state == GameState.MAIN_MENU: gs = sound.Sound(GAME_START_SOUND) gs.play() self.setup() self.state = GameState.PLAYING elif self.state == GameState.MAIN_MENU_CONTROLS: self.state = GameState.MAIN_MENU_CONTROLS_SHOW elif self.state == GameState.GAME_OVER: self.setup() self.state = GameState.MAIN_MENU elif self.state == GameState.MAIN_MENU_CONTROLS_SHOW: self.state = GameState.MAIN_MENU_CONTROLS if key == arcade.key.DOWN: if self.state == GameState.MAIN_MENU: self.state = GameState.MAIN_MENU_CONTROLS elif self.state == GameState.MAIN_MENU_CONTROLS: self.state = GameState.MAIN_MENU if key == arcade.key.UP: if self.state == GameState.MAIN_MENU: self.state = GameState.MAIN_MENU_CONTROLS elif self.state == GameState.MAIN_MENU_CONTROLS: self.state = GameState.MAIN_MENU elif self.state == GameState.PLAYING: # This line below is new. It checks to make sure there is a platform underneath # the player. Because you can't jump if there isn't ground beneath your feet. if self.physics_engine.can_jump(): self.player.change_y = JUMP_SPEED if key == arcade.key.LEFT: if self.state == GameState.PLAYING: self.player.change_x = -MOVEMENT_SPEED self.lastdirection = 'l' if key == arcade.key.RIGHT: if self.state == GameState.PLAYING: self.player.change_x = MOVEMENT_SPEED self.lastdirection = 'r' if key == arcade.key.SPACE: if self.state == GameState.PLAYING and self.temp_state != GameState.GAME_ENDING: if len(self.bullet_list) < 1: mirrored = False change_x = 1 if self.lastdirection == 'l': mirrored = True change_x = -1 for i in range(len(KNIGHT_ATTACK)): self.player.texture = arcade.load_texture( KNIGHT_ATTACK[i], scale=0.6, mirrored=mirrored) if not self.shooting_fire: bullet = Spear(mirrored=mirrored) bullet.center_x = self.player.center_x bullet.center_y = self.player.center_y bullet.change_x = change_x bullet.change_y = 1 self.bullet_list.append(bullet) self.animated_list.append(bullet) else: bullet = Fire(mirrored=mirrored) bullet.center_x = self.player.center_x bullet.center_y = self.player.center_y bullet.change_x = change_x self.bullet_list.append(bullet) self.animated_list.append(bullet) sonic = sound.Sound(FIRE_SOUND) sonic.play()
def initEvents(self, events): self.Sound = sound.Sound(events, self.player)
def __init__(self): self.win = py.display.set_mode( (config.screen_width, config.screen_height)) py.font.init() py.display.set_caption("EscapeVector") #----------Menusystem--------- self.menu_system = menu.Menu() ############ self.mouse_clicked = False self.quit = False self.mouse_pos = (0, 0) self.pressed_escape = False self.turn_right = False self.turn_left = False self.turbo = False self.throttle_down = True self.throttle_up = False self.slowtime = False self.slowduration = 10 self.clock = py.time.Clock() self.hud_base = py.transform.scale(py.image.load("../images/hud.png"), (200, 200)) self.explode = explosion.Explosion() self.minimap = minimap.Minimap() self.missiles_exploded = [] self.close_time = 0 self.fighters = py.sprite.Group() self.missiles = py.sprite.Group() self.emps = py.sprite.Group() self.turn_screen_red = False self.slowvalue = 1 self.bullets = bullet.BulletsSystem() self.enemiesbullets = bullet.BulletsSystem() self.shoot = False self.ai = brain.Brain() self.ai.fighters = self.fighters.sprites() self.sparkSystem = particle.SparkSystem() self.explosions_size = 10 self.initial_explosion = [] self.clouds = clouds.Clouds() self.explosions = [] self.camoffs = [] for i in range(20): self.camoffs.append( [random.randint(-10, 10), random.randint(-10, 10)]) self.camoffx = 0 self.camoffy = 0 self.shake = False self.shakecount = 0 self.screen_r = 0x8c self.screen_g = 0xbe self.screen_b = 0xd6 self.turn_screen_normal = True self.dirty_rects = [] self.game_exists = False #######sounds##### self.sounds = sound.Sound() self.playerhit = False self.fighterhit = False self.ticklowspeed = 0.5 self.tickhighspeed = 0.1 self.tickspeedrate = 0.05 self.tickspeed = 0.1
def load_samples(self): # Reset defaults current_basename = gv.SETLIST_LIST[self.preset_current_loading] voices_this_preset = [] channel = gv.MIDI_CHANNEL gv.pitchnotes = gv.PITCHRANGE_DEFAULT # fallback to the samplerbox default gv.PRERELEASE = gv.BOXRELEASE # fallback to the samplerbox default for the preset release time dirname = os.path.join(gv.SAMPLES_DIR, current_basename) definitionfname = os.path.join(dirname, "definition.txt") sfzfname = glob.glob(os.path.join(dirname, '*.sfz')) sfzfname = sfzfname[0].replace('\\', '/') if sfzfname else '' # file_count = float(len(os.listdir(dirname))) file_count = len(glob.glob1(dirname, "*.wav")) file_current = 1.0 gv.samples[self.preset_current_loading]['keywords'][ 'fillnotes'] = 'Y' # set fillnotes global default because it's needed in this iteration later if os.path.isfile(definitionfname): print 'START LOADING: [%d] %s' % ( self.preset_current_loading, current_basename) # debug definition_list = list(enumerate(open(definitionfname, 'r'))) wav_definitions_list = [ x for x in definition_list if "%%" not in x[1] ] # remove list entries containing %% wav_definitions_list = [ x for x in wav_definitions_list if "\n" != x[1] ] # remove blank lines with open(definitionfname, 'r') as definitionfile: if (self.preset_current_loading != self.preset_current_selected ) or gv.nav.nav_pressed == True: self.pause_if_playingsounds_or_midi() if self.LoadingInterrupt: return ############################ # Global-level definitions # ############################ for i, pattern in enumerate( definitionfile): # iterate every line if (self.preset_current_loading != self.preset_current_selected ) or gv.nav.nav_pressed == True: self.pause_if_playingsounds_or_midi() if self.LoadingInterrupt: return if r'%%' not in pattern: continue try: # Add any found keywords to preset's samples dict without applying to globals if r'%%gain' in pattern: gv.samples[self.preset_current_loading][ 'keywords']['gain'] = abs( float(pattern.split('=')[1].strip())) continue if r'%%transpose' in pattern: gv.samples[self.preset_current_loading][ 'keywords']['transpose'] = int( pattern.split('=')[1].strip()) continue if r'%%release' in pattern: release = (int(pattern.split('=')[1].strip())) if release > 127: print "Release of %d limited to %d" % (release, 127) release = 127 gv.samples[self.preset_current_loading][ 'keywords']['release'] = release continue if r'%%fillnotes' in pattern: m = pattern.split('=')[1].strip().title() if m == 'Y' or m == 'N': fillnotes = m gv.samples[self.preset_current_loading][ 'keywords']['fillnotes'] = fillnotes continue if r'%%pitchbend' in pattern: pitchnotes = abs(int( pattern.split('=')[1].strip())) pitchnotes = sorted([ 0, pitchnotes, 24 ])[1] # limit value to within the range 0-24 gv.samples[self.preset_current_loading][ 'keywords']['pitchbend'] = pitchnotes continue if r'%%mode' in pattern: mode = pattern.split('=')[1].strip().title() if mode == gv.PLAYLIVE \ or mode == gv.PLAYONCE \ or mode == gv.PLAYSTOP \ or mode == gv.PLAYLOOP \ or mode == gv.PLAYLO2X: gv.samples[self.preset_current_loading][ 'keywords']['mode'] = mode continue if r'%%velmode' in pattern: velmode = pattern.split('=')[1].strip().title() if velmode == gv.VELSAMPLE or velmode == gv.VELACCURATE: gv.samples[self.preset_current_loading][ 'keywords']['velmode'] = velmode continue # End of global definitions except Exception as e: if pattern != '': print "Error in definition file, skipping line %s." % ( i + 1) print "Line %d contents: %s" % (i + 1, pattern) # exc_info = sys.exc_info() # print exc_info print( 'Error on line {}'.format( sys.exc_info()[-1].tb_lineno), type(e), e) # Set global variables from definitions or defaults # if self.preset_current_loading != self.preset_current_selected: # self.set_globals_from_keywords() # print '################################' if (self.preset_current_loading != self.preset_current_selected ) or gv.nav.nav_pressed == True: self.pause_if_playingsounds_or_midi() if self.LoadingInterrupt: return with open(definitionfname, 'r') as definitionfile: if (self.preset_current_loading != self.preset_current_selected ) or gv.nav.nav_pressed == True: self.pause_if_playingsounds_or_midi() if self.LoadingInterrupt: return ############################ # Sample-level definitions # ############################ file_list = [] # used for accurate loading percentage feedback for i, pattern in enumerate( definitionfile): # iterate every line (again) if (self.preset_current_loading != self.preset_current_selected ) or gv.nav.nav_pressed == True: self.pause_if_playingsounds_or_midi() if self.LoadingInterrupt: return try: defaultparams = { 'midinote': '0', 'velocity': '127', 'notename': '', 'voice': '1', 'seq': '1', 'channel': gv.MIDI_CHANNEL, 'release': '128', 'fillnote': 'G', 'mode': 'Keyb', 'mutegroup': '0' } if len(pattern.split(',')) > 1: defaultparams.update( dict([ item.split('=') for item in pattern.split( ',', 1)[1].replace(' ', '').replace( '%', '').split(',') ])) pattern = pattern.split(',')[0] pattern = re.escape(pattern.strip()) pattern = pattern \ .replace(r"\%midinote", r"(?P<midinote>\d+)") \ .replace(r"\%channel", r"(?P<channel>\d+)") \ .replace(r"\%velocity", r"(?P<velocity>\d+)") \ .replace(r"\%voice", r"(?P<voice>\d+)") \ .replace(r"\%release", r"(?P<release>[a-zA-Z0-9_])") \ .replace(r"\%fillnote", r"(?P<fillnote>[YNGyng])") \ .replace(r"\%mode", r"(?P<mode>\w+)") \ .replace(r"\%seq", r"(?P<seq>\d+)") \ .replace(r"\%notename", r"(?P<notename>[A-Ga-g]#?[0-9])") \ .replace(r"\%mutegroup", r"(?P<mutegroup>\d+)") \ .replace(r"\*", r".*?").strip() # .*? => non greedy for fname in glob.glob1( dirname, "*.wav"): # iterate over .wav files in the dir if (self.preset_current_loading != self.preset_current_selected ) or gv.nav.nav_pressed == True: self.pause_if_playingsounds_or_midi() if self.LoadingInterrupt: return m = re.match(pattern, fname) if m: ############################ # DISPLAY LOADING PROGRESS # ############################ if self.preset_current_loading == gv.samples_indices[ gv.preset]: if fname not in file_list: file_list.append(fname) percent_loaded = (file_current / file_count) * 100.0 file_current += 1 gv.percent_loaded = percent_loaded # Send percent loaded of sample-set to be displayed self.update_display('loading', timeout=0.3) ############################ info = m.groupdict() voice = int( info.get('voice', defaultparams['voice'])) voices_this_preset.append(voice) release = int( info.get('release', defaultparams['release'])) fillnote = str( info.get('fillnote', defaultparams['fillnote'])).title( ).rstrip() midinote = int( info.get('midinote', defaultparams['midinote'])) channel = int( info.get('channel', defaultparams['channel'])) velocity = int( info.get('velocity', defaultparams['velocity'])) seq = int(info.get('seq', defaultparams['seq'])) notename = info.get('notename', defaultparams['notename']) mode = info.get( 'mode', defaultparams['mode']).rstrip() mutegroup = int( info.get('mutegroup', defaultparams['mutegroup'])) # next statement places note 60 on C3/C4/C5 with the +0/1/2. So now it is C4: if notename: midinote = gv.NOTES.index( notename[:-1].lower()) + ( int(notename[-1]) + 2) * 12 # Ignore loops at the sample level, overriding the global sample_mode mode_prop = None if mode.title( ) == 'Once' or gv.sample_mode.title( ) == 'Once': mode_prop = mode.title() if gv.samples[ self.preset_current_loading].has_key( (midinote, velocity, voice, channel)): """ Sample Randomization by David Hilowitz """ # Find samples marked for randomization (seq). # Check existing list of sound objects if s.seq == seq if any(s.seq == seq for s in gv.samples[ self.preset_current_loading] [midinote, velocity, voice, channel]): # print 'Sequence:%i, File:%s already loaded' % (seq, fname) continue else: if (midinote, velocity, voice, channel ) in gv.samples[ self.preset_current_loading]: gv.samples[self.preset_current_loading][midinote, velocity, voice, channel] \ .append(sound.Sound(os.path.join(dirname, fname), midinote, velocity, seq, channel, release, mode_prop, mutegroup)) print 'Sample randomization: found seq:%i (%s) >> loading' % ( seq, fname) else: gv.samples[self.preset_current_loading][ midinote, velocity, voice, channel] = [ sound.Sound( os.path.join(dirname, fname), midinote, velocity, seq, channel, release, mode_prop, mutegroup) ] # gv.fillnotes[midinote, voice] = fillnote gv.samples[self.preset_current_loading][ 'fillnotes'][midinote, voice] = fillnote # print "sample: %s, note: %d, voice: %d, channel: %d" %(fname, midinote, voice, channel) except Exception as e: if pattern != '': print "Error in definition file, skipping line %s." % ( i + 1) print "Line %d contents: %s" % (i + 1, pattern) # exc_info = sys.exc_info() # print exc_info print( 'Error on line {}'.format( sys.exc_info()[-1].tb_lineno), type(e), e) ############### # SFZ support # ############### elif os.path.isfile(sfzfname): if self.LoadingInterrupt: return # SFZParser by SpotlightKid. https://github.com/SpotlightKid/sfzparser # LICENCE: https://github.com/SpotlightKid/sfzparser/blob/master/LICENSE sfz = SFZParser(sfzfname) # Set globals release = int( (float(sfz.sections[0][1].get('ampeg_release')) * 1000) / 17) release = sorted([0, release, 127])[1] # limit value to within the range 0-127 gain = float(sfz.sections[0][1].get('volume')) + 1.0 sustain = int(sfz.sections[0][1].get('ampeg_sustain')) # unused decay = float(sfz.sections[0][1].get('ampeg_decay')) # unused attack = float(sfz.sections[0][1].get('ampeg_attack')) # unused gv.samples[ self.preset_current_loading]['keywords']['release'] = release gv.samples[self.preset_current_loading]['keywords']['gain'] = gain print '>>>> Global release:', release print '>>>> Global gain:', gain voices_this_preset.append(1) file_list = [] # Used for accurate loading percentage feedback for section in sfz.sections: if (self.preset_current_loading != self.preset_current_selected ) or gv.nav.nav_pressed == True: self.pause_if_playingsounds_or_midi() if self.LoadingInterrupt: return if type(section[0]) == unicode: if section[0] == 'region': sample_fname = section[1].get('sample') sample_path = os.path.join(dirname, sample_fname) hivel = int(section[1].get('hivel')) lovel = int(section[1].get('lovel')) # unused midinote = int(section[1].get('pitch_keycenter')) hikey = int(section[1].get('hikey')) # unused lokey = int(section[1].get('lokey')) # unused gv.samples[self.preset_current_loading][ midinote, hivel, 1, 1] = [ sound.Sound(sample_path, midinote, hivel, 1, 1, release, None, 0) ] gv.samples[self.preset_current_loading]['fillnotes'][ midinote, 1] = 'Y' ############################ # DISPLAY LOADING PROGRESS # ############################ if self.preset_current_loading == gv.samples_indices[ gv.preset]: if sample_fname not in file_list: file_list.append(sample_fname) percent_loaded = (file_current / file_count) * 100.0 file_current += 1 gv.percent_loaded = percent_loaded # Send percent loaded of sample-set to be displayed self.update_display('loading', timeout=0.2) ############################ # If no definition.txt or *.sfz file found in folder, look for numbered files (64.wav, 65.wav etc) or notenamed files (C1.wav, D3.wav etc) else: for midinote in range(0, 127): if (self.preset_current_loading != self.preset_current_selected ) or gv.nav.nav_pressed == True: self.pause_if_playingsounds_or_midi() if self.LoadingInterrupt: return voices_this_preset.append(1) file_midinote = os.path.join(dirname, "%d.wav" % midinote) notename_index = midinote % 12 octave = str((midinote / 12)) notename = gv.NOTES[notename_index] + octave file_notename = os.path.join(dirname, "%s.wav" % notename) if os.path.isfile(file_midinote): # print "Processing " + file_midinote gv.samples[self.preset_current_loading][ midinote, 127, 1, channel] = [ sound.Sound(file_midinote, midinote, 127, 1, channel, gv.BOXRELEASE, None, 0) ] elif os.path.isfile(file_notename): # print "Processing " + file_notename gv.samples[self.preset_current_loading][ midinote, 127, 1, channel] = [ sound.Sound(file_notename, midinote, 127, 1, channel, gv.BOXRELEASE, None, 0) ] gv.samples[self.preset_current_loading]['fillnotes'][midinote, 1] = 'Y' ############################ # DISPLAY LOADING PROGRESS # ############################ if self.preset_current_loading == gv.samples_indices[ gv.preset]: percent_loaded = float((midinote + 1) / 128) * 100.0 gv.percent_loaded = percent_loaded # Send percent loaded of sample-set to be displayed self.update_display('loading', timeout=0.2) ############################ if self.preset_current_loading != gv.samples_indices[gv.preset]: time.sleep(0.01) # Record number of voices because if preset is loaded into mem, its voices don't get detected again # Remove duplicates by converting to a set. ie [1, 1, 1, 2, 2, 1, 4, 3] => [1, 2, 4, 3] gv.samples[self.preset_current_loading]['keywords']['voices'] = list( set(voices_this_preset)) if (self.preset_current_loading != self.preset_current_selected) or gv.nav.nav_pressed == True: self.pause_if_playingsounds_or_midi() if self.LoadingInterrupt: return # All samples loaded - mark as True gv.samples[self.preset_current_loading]['samples_loaded'] = True
import sound import stereosound_1 as myfile # ??? should be replaced with the name of #the file which has your functions. #Read the statements and comments below. #You will need to make appropriate changes to the statements #to work with different wav files and test various functions #you have written. #Converts the sound in grace.wav file to a Sound object. snd = sound.Sound(filename='water.wav') #The function fade that you have written is called #and the Sound object it returns is assigned to gracefade. waterfaded = myfile.fade_in(snd, 268128.0) #The Sound object gracefade is converted to sound in #a wav file called grace_fade.wav. #This wav file did not exist before but is newly created. waterfaded.save_as('waterfadeds.wav')
__author__ = "Ryan Bergeron" from discord.ext import commands from prefix import prefixes import discord, dnd, fun, prefix, sound, utility # Function will determine server's prefix def GetPrefix(bot, message): return prefix.GetPrefix(bot, message, prefixes) # Set bot and commands bot = commands.Bot(command_prefix=GetPrefix) bot.add_cog(dnd.DnD(bot)) bot.add_cog(fun.Fun(bot)) bot.add_cog(prefix.Utility(bot)) bot.add_cog(sound.Sound(bot)) bot.add_cog(utility.Utility(bot)) # When the bot is running, output to console and set activity @bot.event async def on_ready(): print("Logged on as {0.user}!".format(bot)) await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="you sleep, very cool!")) # Attempt to read in the token from text file try: f = open("token.txt", 'r') bot.run(f.read()) except: print("token.txt does not exist!") exit()