def run(self): def tone_gen(): """Generate approximately dt's worth of tone. attempts to Start/stop when signal is near zero, to avoid glitches. this doesnt really work""" #foolish overoptimization f = self.f dt = self.dt fs = self.fs sin = numpy.sin floor = numpy.floor y = numpy.zeros_like(self.t) for ft, vol in f.values(): y += (vol * sin(2 * numpy.pi * ft * self.t)) #scale so we dont compress scaling = 1.0 / max([max(y), 1.0]) return (128 + 127 * y * scaling).astype('u1').tostring() def gen_file(file): tone = tone_gen() file.seek(0, 0) wf = wave.open(file, 'w') wf.setparams((1, 1, self.fs, 0, 'NONE', 'not compressed')) wf.writeframes(tone) wf.close() # to optimize loop performance, dereference everything ahead of time filelist = self.filelist playerlist = [None, None] idx = self.idx dt = self.dt gen_file(filelist[idx]) playerlist[idx] = sound.Player(filelist[idx].name) tic = time.time while self.alive: t0 = tic() #1) play playerlist[idx].play() idx = (idx + 1) % 2 #2) generate gen_file(filelist[idx]) #3) load p = playerlist[idx] = sound.Player(filelist[idx].name) #4) sleep try: #we want to sleep just long enough to start next player # this is trial and error.... time.sleep(0.99 * (t0 + dt - tic())) #time.sleep((p.duration-p.current_time)*0.5) except: pass self.cleanup()
def run(self): self.music = sound.Player('Musics/EntityFall-menu.m4a') while ct.LAUNCHED: if not ct.STARTED and ct.LAUNCHED: self.music.play() else: self.music.stop() break self.music.stop() self.music = sound.Player('Musics/EntityFall-fight.m4a') while ct.STARTED: self.music.play() self.music.stop()
def start(self, play=False): while True: self.file = tempfile.mkstemp('.m4a')[1] print(self.file) self._recorder = sound.Recorder(self.file) self._recorder.record(self.SECONDS) # loop clips wait_until(self.finished, self.SECONDS + 1, 0.1) self._stats() if play and self.DEBUG: print('Replaying...', ) player = sound.Player(self.file) player.play() print(player.duration) os.remove(self.file) #if threshold reached, call if self.louder_than(): if self.DEBUG: print('🚼 CALLING MUMMY !!! 🔔🔔🔔') else: self._call()
def AUTOTYPE_FUNC(browser, file_path, title=None, **kwargs): import sound sound_player = sound.Player(file_path) if sound_player.duration: from ..SoundPlayer import SoundPlayerPane return SoundPlayerPane, args(sound_player, title=title, name=file_path), 1
def set_player(): global P # if P is not None: # stop() # P.done() P = sound.Player( path=sounds[config['now_page']] )
def test(self, song): self.player = sound.Player(song) t = self.player.duration self.start.acquire() self.player.play() #self.player.current_time=60 while self.player.current_time < t - .1 and self.playing: time.sleep(.1) self.player.stop() self.start.release() self.playing = False
class Game(scene.Scene): music_dir = 'Music/' background_music = [ 'TRG_Banks_-_06_-_Goodbye_Machineryhead.mp3', 'David_Szesztay_-_Beach_Party.mp3' ] os.chdir(music_dir) sound_player = sound.Player(background_music[1]) os.chdir('..') def setup(self): pass def update(self): #Performs any scene-specific updates that need to occur before scene actions are evaluated. #self.move(box,(0,5)) #self.move(self.box,(0,5)) self.move(player, (1, 0)) self.move(player2, (-1, 0)) self.jump(box) def stop(self): #Gets called automatically when the home button is pressed while a scene is running. self.sound_player.stop() def pause(self): #Gets called automatically when the home button is pressed while a scene is running. pass def touch_began(self, touch): #This method is called when a touch begins on the scene’s view pass def touch_moved(node, touch): #This method is called when a touch moves in the scene’s view pass def touch_ended(node, touch): #This method is called when a touch ends in the scene’s view pass # CUSTOM METHODS def move(self, node, direction): node.center += direction def jump(self, node): node.run_action(scene.Action.move_by(20, 20, 1)) def pause_game(self, sender): if sender.value == True: sv.paused = True else: sv.paused = False
def playButton_tapped(sender): # so sound will play when playButton_tapped function returns, if not a global it is destroyed otherwise, maybe using asyncio would get it to work too. global global_soundPlayerObj if sender.title == "Play": if len(v["recordingToPlay_or_Xform"].text) > 0 : file = getWaveFile(v["recordingToPlay_or_Xform"].text) if file == None: # file entered was not found. v['recordingsView'].text = "That file does not exist." sound.play_effect('game:Error') else: # file exists, so play it. playClickSound() sender.title = "Stop Play" global_prevValues["playButton_image"] = sender.image sender.image = ui.Image("iob:stop_24") global_prevValues["playButton_prevBkGrnd_color"] = sender.background_color sender.background_color = "#ff2b62" v["recordingToPlay_or_Xform"].text = file.split('/')[3] v['recordingsView'].text = v["recordingToPlay_or_Xform"].text + " being played" # create the waveform image from the sound file and display it (Time Domain) # pass the wave file to read, and the imageView area to display it in waveViewTD(file, v['waveFormView']) print("type:", type(v['waveFormView'])) global_soundPlayerObj = sound.Player(file) global_soundPlayerObj.play() #asyncio(restorePlayButton()) #does not work right else : # user has not entered a file to play yet. v['recordingsView'].text = "No file selected." sound.play_effect('game:Error') else: # sender.title == "Stop Play", so reset button to "Play" state v['waveFormView'].send_to_back() if global_soundPlayerObj.playing: global_soundPlayerObj.stop() playClickSound() sender.title = "Play" sender.image = global_prevValues["playButton_image"] sender.background_color = global_prevValues["playButton_prevBkGrnd_color"] v['recordingsView'].text = "" # clear text of what was previously playing.
def XformRecording(self): originalRec, singerRec = getWaveFiles(self) # get the wave files the user selected # now get the raw data from each of them, # convert to mono if stereo before returning the data originalData = getWaveFileData(originalRec) print("\noriginal data", originalData[0:10], "...", originalData[-10:]) singerData = getWaveFileData(singerRec) print("\nsinger data", singerData[0:10], "...", singerData[-10:]) # YOU ARE HERE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! XformedData = processData(originalData, singerData) print("\nXformed data", XformedData[0:10], "...", XformedData[-10:]) fileName = None XformedRec = writeWaveFile(XformedData, path2_transformedVoices, fileName) return sound.Player(XformedRec)
def main(wav_file): # checking if this script is run properly (as an iOS extension) if not appex.is_running_extension(): print('This script is intended to be run from the sharing extension.') return None # gets selected picture picture = appex.get_image(image_type='pil') if not picture: print('No input image') return None # main operation of conversion and creating wav file pixels = np.array(Image.open(picture)) audio = picture_to_wave.image_to_sound(pixels) picture_to_wave.save_wav(wav_file, audio) # playing just created wav file sound.set_volume(1) player = sound.Player(wav_file) player.play()
def __init__(self): self.music = sound.Player('Music/FranticLevel.m4a') self.music.number_of_loops = -1 self.music.volume = 0.1 self.game_paused = True self.background_color = '#ccf4f7' self.tiled_bg = sk.TiledSpriteNode(bg_texture, (1024, 512)) self.tiled_bg.position = 512, 256 self.add_child(self.tiled_bg) self.t = 0 self.ground_t = 0 self.standing = False self.jump_t = 0 self.jump_down = False self.game_over = False self.game_finished = False self.score = 0 self.highscore = 0 self.last_score = 0 try: with open('.Highscore.txt', 'r') as f: self.highscore = int(f.read()) except IOError: pass self.jetpack_active = False self.jetpack_fuel = 0 self.v = sk.Vector2(0, 0) self.player_speed = 4 self.player = player_and_effects['player'][0].__copy__() self.player.position = 50, 97 self.jetpack = self.player['jetpack'][0] self.jetpack['jetpack_flame'][0].hidden = True self.jetpack.alpha = 0 self.player.z_position = 2 self.player_sprite = self.player['sprite'][0] self.foreground_layer = sk.Node() self.foreground_layer.x_scale = zoom self.foreground_layer.y_scale = zoom self.foreground_layer.add_child(self.player) self.dust_effect = player_and_effects['dust'][0].__copy__() self.dust_effect.num_particles_to_emit = 0 self.foreground_layer.add_child(self.dust_effect) self.add_child(self.foreground_layer) self.levels = [] self.load_levels() self.score_hud = ScoreHUD() self.add_child(self.score_hud) self.highscore_label = sk.LabelNode() self.highscore_label.font_name = 'Avenir Next Condensed' self.highscore_label.font_size = 17 self.highscore_label.font_color = '#68c3d1' self.highscore_label.text = 'last: 0 / high: %i' % self.highscore self.add_child(self.highscore_label) paused_label = sk.LabelNode() paused_label.font_name = 'Avenir Next Condensed' paused_label.font_size = 50 paused_label.text = 'Tap to play' self.paused_overlay = sk.SpriteNode() self.paused_overlay.size = 1024, 1024 self.paused_overlay.color = (0, 0, 0, 0.4) self.paused_overlay.z_position = 10 self.paused_overlay.add_child(paused_label) self.add_child(self.paused_overlay)
for fret,string,dead_note in zip(frets,strings,dead_notes): if dead_note: continue octave,tone = divmod(string + fret,12) tones.append((tone,octave+baseOctave)) for tone,octave in tones: sound.play_effect(getWaveName(tone,octave)) time.sleep(model.play_arpSpeed*0.25) time.sleep(3*model.play_arpSpeed) # rest between chords # the "chords" play just fine as well as the final sleeps between chords. # -------------------- import sound,ui v=ui.View() v.bg_color='red' v.present() p=sound.Player('piano:A3') def g(): v.bg_color='green' p.finished_handler=None p.play() def f(): v.bg_color='blue' p.finished_handler=g p.play() p.finished_handler=f p.play() # --------------------
def main(): # initialize drink_status = False drunk_level = 0 bill = 0 while (drink_status == False): # display menu print("++++") print("Menu") print("") for drink in staff_action["menu"]["drink"].keys(): print(drink) print("++++") # take a order speech.say("ご注文をどうぞ!", 'ja-JP') time.sleep(1.8) recorder = sound.Recorder('speech.m4a') recorder.record() dialogs.alert('注文が終わったらボタンをタップしてください.', '', 'Finish', hide_cancel_button=True) recorder.stop() # replay voice = sound.Player('speech.m4a') voice.play() time.sleep(5.0) # recognize order try: result = speech.recognize('speech.m4a', 'ja-JP') except RuntimeError as e: print("recognition failed: %s" % (e, )) # order done hit = False for candidate in staff_action["menu"]["drink"].keys(): if candidate in result[0][0]: string = 'お待たせしました、' + candidate + 'です!' speech.say(string, 'ja-JP') print(string) # add bill and drunk_level bill += staff_action["menu"]["drink"][candidate]["price"] drunk_level += staff_action["menu"]["drink"][candidate]["alc"] hit = True break if not hit: string = "申し訳ありません、当店には取りあつかいがありません。" speech.say(string, 'ja-JP') print(string) # check drunk_level if (drunk_level >= drunk_threshold): string = "あ、お茶をお出ししますね。" speech.say(string, 'ja-JP') string = "お会計は" + str(bill) + "円です。お気をつけておかえりください。" speech.say(string, 'ja-JP') drink_status = True time.sleep(2.0)
def setup(self): self.player = sound.Player( os.path.expanduser('~/Pythonista.app/Beep.caf')) self.player.number_of_loops = -1 #repeat forever self.playing = False
from objc_util import * from time import sleep from datetime import datetime import requests from speech import say import sound import os import urllib urlprefix = "http://example.com/battery" UIDevice = ObjCClass("UIDevice") UIDevice.currentDevice().setBatteryMonitoringEnabled(True) if not os.path.exists("10silence.mp3"): urllib.request.urlretrieve(urlprefix + "10silence.mp3", "10silence.mp3") player = sound.Player("10silence.mp3") player.number_of_loops = -1 player.play() while True: req = requests.request( "GET", urlprefix + str(UIDevice.currentDevice().identifierForVendor().UUIDString()) + "/" + (datetime.now().isoformat()) + "/" + str(UIDevice.currentDevice().batteryLevel())) sleep(5) player.stop()
def setup(self): self.bm = [ l.strip() for l in open(self.folder + '/' + self.song, 'r').readlines() ] self.cols = [] for i, j in enumerate(self.bm): if j[:13] == 'ApproachRate:': self.ar = ar( min( 10, float(j[13:]) * (1.4 if self.hr else (.5 if self.ez else 1)))) if j[:11] == 'CircleSize:': self.cs = cs( min( 10, float(j[11:]) * (1.4 if self.hr else (.5 if self.ez else 1))) - 1) if j[:18] == 'OverallDifficulty:': self.od = od( min( 10, float(j[18:]) * (1.4 if self.hr else (.5 if self.ez else 1))) - 2) if j[:15] == 'AudioFilename: ': audiofile = self.audiofile = self.folder + '/' + j[15:] if j[:14] == 'StackLeniency:': stackl = float(j[14:]) if j[:13] == 'AudioLeadIn: ': self.leadin0 = self.leadin = float(j[13:]) / 1000 if j[:17] == 'SliderMultiplier:': self.sliderx = sliderx = float(j[17:]) if j[:15] == 'SliderTickRate:': self.tickrate = float(j[15:]) r = re.sub('Combo\d : ', '', j) if r != j: self.cols.append(tuple(float(k) / 255 for k in r.split(','))) if j == '//Background and Video events': bgpic = self.bm[i + 1].split(',')[2][1:-1] if j == '//Break Periods': if self.bm[i + 1][0] == '/': self.breaks = [] else: self.breaks = [ float(k) / 1000 for k in self.bm[i + 1].split(',') ] if j == '[TimingPoints]': timingi = i + 1 if j == '[HitObjects]': break if not self.cols: self.cols = [(1., 192. / 255, 0.), (0., 202., 0.), (18. / 255, 124. / 255, 1.), (242. / 255, 24. / 255, 57. / 255)] self.tpts = [] for l in self.bm[timingi:i]: if l == '[Colours]' or l == '': break stuff = [float(a) for a in l.split(',') if a] if stuff[6] == 0 and self.tpts: stuff[6] = self.tpts[-1][0] else: stuff[6] = stuff[0] self.tpts.append( (stuff[0] / 1000., stuff[1] / 1000 if stuff[1] > 0 else self.tpts[-1][1], -100. / stuff[1] if stuff[1] < 0 else 1, stuff[6], stuff[7] == 1, int(stuff[3]), int(stuff[4]), int(stuff[5]) / 100.)) #tpts[n]=[time,beatlength,velocity,lasttime,kiai,sampletype,sampleset,volume] self.tptn = 0 self.objs = [i.split(',') for i in self.bm[i + 1:]] self.ct = len(self.objs) self.ts = [int(i[2]) / 1000. for i in self.objs] self.x = [float(i[0]) for i in self.objs] self.y = [(float(i[1]) if self.hr else 384 - float(i[1])) for i in self.objs] #self.hitsounds=[int(i[4]) for i in self.objs] otypes = [(int(i[3]) & 11, int(i[3]) & 4, [int(i[4])]) for i in self.objs] self.hitdata = [ [-1, -1] for i in range(self.ct) ] #[hit time, hit type] hit types: -1: not hit yet, 300, 100, 50, 0 self.disp = [0] * self.ct #self.cols=[(1,1,1)] self.cols = [(200 / 255., 200 / 255., 1), (0, 1, 100 / 255.), (200 / 255., 100 / 255., 100 / 255.), (100 / 255., 1, 100 / 255.)] #Parse Object Types and Colors self.otypes = [] n = 0 n2 = 1 for i, j, k in otypes: if j: n += 1 n %= len(self.cols) n2 = 1 self.otypes.append((i, n, n2, k)) n2 += 1 #Stacking prev = self.x[0], self.y[0] tprev = self.ts[0] n = 0 stacks = [0] * self.ct for i in range(1, self.ct): if (self.x[i], self.y[i]) == prev and self.ts[i] - tprev < stackl / 3: n += 1 stacks[i] = n else: n = 0 prev = self.x[i], self.y[i] tprev = self.ts[i] for i in range(self.ct): self.x[i] += stacks[i] * self.cs / 24 self.y[i] -= stacks[i] * self.cs / 24 #Sliders self.sd = [] self.si = {} n = 0 for i, j in enumerate(self.objs): if self.otypes[i][0] == 2: t = float(j[2]) / 1000 while n < len(self.tpts) - 1 and self.tpts[n + 1][0] <= t: n += 1 c = j[5].split('|') t = c[0] c = [k.split(':') for k in c[1:]] c = [(self.x[i], self.y[i])] + [(float( k[0]), (float(k[1]) if self.hr else 384 - float(k[1]))) for k in c] l = float(j[7]) if t == 'L': p = sliderlib.line(c, l)[0] if t == 'B': p = sliderlib.bezier(c, l) if t == 'P': p = sliderlib.passthrough(c, l) pxpb = sliderx * 100 * self.tpts[n][2] r = int(j[6]) sbl = r * l / pxpb self.sd.append([ p, sbl * self.tpts[n][1], r, n, l, pxpb / self.tickrate, self.tpts[n][1] / self.tickrate ]) self.si[i] = 0 #sd[n]=[data,duration,repeats,timingpoint#,pxlen,px/tick,tick interval] #si[n]=[image, pos] else: self.sd.append(0) self.sliderinput = {i: [] for i in self.si} #self.slideredge=(1,1,1) self.slideredge = (200 / 255., ) * 3 #self.sliderfill=None self.sliderfill = (0, 0, 0) self.i = 0 self.i2 = 0 self.stopped = False self.paused = False self.background_color = (0, 0, 0) self.a = Node((cs(0) + 112, 96), scale=1.3) self.add_child(self.a) self.test = LabelNode(position=self.bounds.center()) #self.add_child(self.test) self.acclabel = Node(position=(self.bounds.w - 100, self.bounds.h - 100)) #self.acclabel.anchor_point=(1,1) self.add_child(self.acclabel) self.combolabel = Node(position=(0, 10)) self.combolabel.anchor_point = (0, 0) self.add_child(self.combolabel) #self.add_child(self.tlabel) self.curtouch = None self.btn = 0 self.combo = 0 self.combotemp = 0 self.cur = SpriteNode('Skin/cursor.png', scale=.5) self.a.add_child(self.cur) self.err = LabelNode('0', ('TrebuchetMS', 12), position=(self.bounds.w / 2, 0)) self.err.anchor_point = (0.5, 0) self.add_child(self.err) self.inputarea = SpriteNode(position=(0, self.bounds.height / 2), alpha=.3) self.inputarea.size = (112, 400) self.inputarea.anchor_point = (0, .5) self.rpm = 0 self.spinnert = 0 self.acc1 = 0. self.acc2 = 0. self.acc0 = 100. self.add_child(self.inputarea) self.bgdim = .75 self.bgdim = max(1 - self.bgdim, .001) try: self.bg = bg = IOps.fit( Image.open(self.folder + '/' + bgpic, ).convert('RGBA'), (1024, 748), 1) with io.BytesIO() as bIO: bg.save(bIO, 'PNG') bg = ui.Image.from_data(bIO.getvalue()) self.bg = SpriteNode(Texture(bg), self.bounds.center(), -1, alpha=.5) self.add_child(self.bg) except: self.bg = Node() #self.load_sliders() Thread(target=self.load_sliders).start() time.sleep(self.ar * 2 + 1) self.player = sound.Player(audiofile) Timer(self.leadin, self.playsong).start()
def loadSound(self): self.useSound = True if self.useSound: self.soundPlayer = sound.Player('Dungeon Game 1.wav') self.soundPlayer.play()
import ui import sound import time #standard beep sound, found on the internet beep = sound.Player('Beep.mp3') #morse code alphabet: 1 unit for dot, 3 units for dash alphabet = { 'a': (1, 3), 'b': (3, 1, 1, 1), 'c': (3, 1, 3, 1), 'd': (3, 1, 1), 'e': (0, 1), 'f': (1, 1, 3, 1), 'g': (3, 3, 1), 'h': (1, 1, 1, 1), 'i': (1, 1), 'j': (1, 3, 3, 3), 'k': (3, 1, 3), 'l': (1, 3, 1, 1), 'm': (3, 3), 'n': (3, 1), 'o': (3, 3, 3), 'p': (1, 3, 3, 1), 'q': (3, 3, 1, 3), 'r': (1, 3, 1), 's': (1, 1, 1), 't': (0, 3), 'u': (1, 1, 3), 'v': (1, 1, 1, 3),
from pathlib import Path import sound import ui root_str = '/System/Library/Audio/UISounds/' root_path = Path(root_str) all_files = list(root_path.glob('**/*.*')) all_sounds = [sound.Player(str(s)) for s in all_files] all_names = [ f'{n: 04}: ' + str(name).replace(root_str, '').replace('/', ' - ') for n, name in enumerate(all_files) ] class View(ui.View): def __init__(self, *args, **kwargs): ui.View.__init__(self, *args, **kwargs) self.data_source = ui.ListDataSource(all_names) self.table_view = ui.TableView() self.table_view.data_source = self.data_source self.table_view.delegate = self self.table_view.flex = 'WH' self.add_subview(self.table_view) # xxx: ここで作るのもなぁ、、、 def tableview_did_select(self, tableview, section, row): print(all_files[row])
# Created by: Kay Lin # Created on: Jan 2018 # Created for: ICS3U # This holds all global variables. import sound pressed_pause = False music_on = True game_over = False game_win = False main_menu_music = sound.Player('assets/sounds/Squareland.wav') game_over_music = sound.Player('assets/sounds/Probably Game Over (Loop).wav') #game_win_music = sound.Player('assets/sounds/')
# coding: utf-8 # https://forum.omz-software.com/topic/2016/unlimited-backgrounding/10 import sound import os import urllib # download a silent mp3 if it's not there yet: if not os.path.exists('silence.mp3'): urllib.urlretrieve('http://www.xamuel.com/blank-mp3-files/1sec.mp3', 'silence.mp3') player = sound.Player('silence.mp3') player.number_of_loops = -1 # repeat forever player.play() # do background stuff... # when you're done: player.stop() # -------------------- # sound.Player.number_of_loops = -1 # -------------------- from sound import Player player = Player('') player.number_of_loops = -1 player.play()
# Created by: Luca # Created on: jan 2018 # Created for: ICS3U #this is the config scene import sound # these are varibules around the whole program music_is_on = True music = sound.Player('images/RetroflexionFINAL.mp3') ship_type = './images/usership1.png' game_over = False
# Created by: Sidney Kang # Created on: Jan 2018 # Created for: ICS3U # This holds all global variables. import sound level_difficulty = 0 gender_type = './assets/sprites/boy_thief.PNG' music_on = True sound_effects_on = True game_over = False game_won = False home_menu_pressed = False restart_game = False ran_once = False main_menu_music = sound.Player('assets/sounds/main_menu_music.mp3') main_game_music = sound.Player('assets/sounds/main_game_music.mp3')
from scene import * from threading import Timer import random import sound import atexit A = Action s = 4 ground = 0 music = sound.Player('Reggea.wav') music.number_of_loops = -1 music.play() run_textures = [] for i in range(0, 8): run_textures.append(Texture('run/' + str(i) + '.png')) jump_textures = [] for i in range(0, 8): jump_textures.append(Texture('jump/' + str(i) + '.png')) fall_textures = [] for i in range(0, 8): fall_textures.append(Texture('fall/' + str(i) + '.png')) bunny_textures = [] for i in range(0, 10): bunny_textures.append(Texture('bun/' + str(i) + '.png')) class background(SpriteNode):