def playPop(): randomsong = random.choice(os.listdir("Playlists/Masterlist")) mixer.music.load("Playlists/Masterlist/" + randomsong) mixer.music.play() mixer.get_busy() while mixer.music.get_busy() == True: continue
def play_sound(data, frequency=44100, size=2, n_channels=2, wait=True, **kwargs): """Plays sound using Pygame. Parameters ---------- data : np.ndarray Data array of the sound to play. frequency : int Number of frames per second. """ from pygame import mixer if mixer.get_busy(): mixer.quit() mixer.init(frequency=frequency, size=size, channels=n_channels) pg_sound = mixer.Sound(array=data) pg_sound.play(**kwargs) if wait: time.sleep(wait) return pg_sound
def play_file_suspects(page=None, gender='f'): d = [] if page == OpeningPage: d.append(mixer.Sound(sounds_path + 'opening_%s.wav' % gender)) elif page == PageOne: d.append(mixer.Sound(sounds_path + 'diamonds_intro_0_%s.wav' % gender)) d.append(mixer.Sound(sounds_path + 'diamonds_intro_1.wav')) d.append(mixer.Sound(sounds_path + 'intro0_3%s.wav' % gender)) d.append(mixer.Sound(sounds_path + 'rate_suspects.wav')) elif page == PageTwo: d.append(mixer.Sound(sounds_path + 'suspects_c_d.wav')) elif page == PageThree: d.append(mixer.Sound(sounds_path + 'rate_suspects.wav')) elif page == PageFour: d.append(mixer.Sound(sounds_path + 'suspect_b_d.wav')) elif page == PageFive: d.append(mixer.Sound(sounds_path + 'rate_all_10_%s.wav' % gender)) elif page == PageSix: d.append(mixer.Sound(sounds_path + 'who_did_it.wav')) elif page == PageSeven: d.append(mixer.Sound(sounds_path + 'robot_detective_%s.wav' % gender)) for i in d: while mixer.get_busy(): pass i.play()
def play_song(self): mixer.init() for song in self.parent_frame.songs_to_play: print 'playing song!!!!!!!' mixer.music.load(song) mixer.music.play() print 'busy:' + str(mixer.get_busy())
def text_to_audio(mytext): from gtts import gTTS # This module is imported so that we can # play the converted audio import os import pygame from pygame import mixer import random # Load the popular external library # Language in which you want to convert language = 'en' print(mytext) # Passing the text and language to the engine, # here we have marked slow=False. Which tells # the module that the converted audio should # have a high speed myobj = gTTS(text=mytext, lang=language, slow=False) # Saving the converted audio in a mp3 file named # welcome audio_name = str(random.random() * 10**10) + ".mp3" myobj.save(audio_name) mixer.init() mixer.music.load(audio_name) channel = mixer.music.play() while mixer.get_busy() == True: continue
def playSound(soundfile, blocking = True, scene = None): """Play sound through default mixer channel in blocking manner. This will load the whole sound into memory before playback """ if not os.path.exists(soundfile): print(("Sound file " + soundfile + " doesn't exists.")) return if blocking: print(("Starting playback " + soundfile + " blocking")) else: print(("Starting playback " + soundfile)) if scene: sound = scene.cache.preloadSound(soundfile) else: sound = mixer.Sound(soundfile) clock = pygame.time.Clock() sound.play() if blocking: while mixer.get_busy(): clock.tick(vinfo.framerate) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit()
def playNote(note, amplitude, duration): new_note = Note(note, amplitude) new_note.play(-1, duration) while (get_busy()): #print(get_busy()) #pass print() new_note.stop()
def play_sound(soundfile, soundplay): if soundplay: mixer.init() for x in range(soundplay): sound = mixer.Sound(soundfile) sound.play() while mixer.get_busy(): sleep(0.5)
def ex_002_pushButtonGetSound_n_LedOn(): while True: # If button is pressed, turn on LED and play sound current_state = GPIO.input(btn_pin) if (current_state == False) and (prev_state == True): if mixer.get_busy(): sound.stop() else: GPIO.output(led_pin, GPIO.HIGH) sound.play() # Only turn off LED if sound has stopped playing if mixer.get_busy() == False: GPIO.output(led_pin, GPIO.LOW) # Save state of switch to use in next iteration of the loop prev_state = current_state
def play(ono_sound, ono_print=True, ono_block=True): """ Play an onomatopoeia 's'. If 'p' is true, also print onomatopoeia to screen. Called by individual onomatopoeia methods. If 'b' is true, block until audio completes playback. """ if ono_print: onomatopoeia_log(ono_sound) onomatopoeia[ono_sound].play() while mixer.get_busy() and ono_block: time.sleep(.1) #this is bad bad bad. Python needs a sched_yield() method
def load_music(self, music): if music != self.music: mixer.music.stop() self.playing = False mixer.music.unload() mixer.music.load(assets.path_to("sounds", music)) if not mixer.get_busy(): mixer.music.play(-1) mixer.music.set_volume(self.current_music_volume) self.playing = True self.music = music
def play(self, start=0, stop=None): # start and stop are in seconds """Use pygame to play the audio. If the audio hasn't been read yet, do that first. """ if stop is None: stop = self.dur() start = int(start * self.sample_rate) stop = int(stop * self.sample_rate) while mixer.get_busy(): pass playAudio(self.audio[start:stop], self.sample_rate)
def play(self, itemNr): if itemNr in SOUNDS.DICTMUSIC: if not self.currentlyPlayingId == itemNr: # requested song is already playing if mix.get_busy(): # mixer currently playing mix.music.fadeout(SOUNDS.SOUND_FADEOUT_TIME) # fadeout current song self.currentlyPlayingId = itemNr mix.music.load(SOUNDS.DICTMUSIC[itemNr]) mix.music.play(loops=-1) # loop indefinetely else: pass # requested song is already playing else: mix.music.fadeout(SOUNDS.SOUND_FADEOUT_TIME) # no song requested
def check_busy(self): """ When music is not playing and mixer is not busy Music starts and music volume is set """ if not mixer.get_busy() and not self.playing: mixer.music.play(-1) mixer.music.set_volume(self.current_music_volume) self.playing = True """ If: Music volume decreases when a sound is playing Elif: Music volume gets its current value when sound stops """ if mixer.get_busy() and not self.changed: mixer.music.set_volume(self.current_music_volume * 0.6) self.changed = True elif not mixer.get_busy() and self.changed: mixer.music.set_volume(self.current_music_volume) self.changed = False
def test_button(self): "test to see if button is being held down" if self.sound is None: return from pygame import mixer if self.play_button_down: if mixer.get_busy(): wx.CallLater(0.1, self.test_button) else: self.looping = True (Opioid2D.Delay(0) + \ Opioid2D.CallFunc(self.sound.play,loops=-1)).do() wx.CallLater(0.1, self.test_button) elif self.looping: self.sound.stop()
def test_button(self): "test to see if button is being held down" if self.sound is None: return from pygame import mixer if self.play_button_down: if mixer.get_busy(): wx.CallLater(0.1, self.test_button) else: self.looping = True (Opioid2D.Delay(0) + Opioid2D.CallFunc(self.sound.play, loops=-1)).do() wx.CallLater(0.1, self.test_button) elif self.looping: self.sound.stop()
def collide(p1, p2): """ Tests whether two particles overlap If they do, make them bounce, i.e. update their angle, speed and position """ dx = p1.x - p2.x dy = p1.y - p2.y dist = math.hypot(dx, dy) if dist < p1.size + p2.size: angle = math.atan2(dy, dx) + 0.5 * math.pi if p1.mass == p2.mass: p1.mass += 1 total_mass = p1.mass + p2.mass (p1angle, p1speed) = addVectors( (p1.angle, p1.speed * (p1.mass - p2.mass) / total_mass), (angle, 2 * p2.speed * p2.mass / total_mass)) (p2angle, p2speed) = addVectors( (p2.angle, p2.speed * (p2.mass - p1.mass) / total_mass), (angle + math.pi, 2 * p1.speed * p1.mass / total_mass)) (p2.angle, p2.speed, p1.angle, p1.speed) = (p2angle, p2speed, p1angle, p1speed) elasticity = p2.elasticity * p1.elasticity total_speed = (p1.speed + p2.speed) p1.hitpoints -= elasticity * 2 p2.hitpoints -= elasticity * 2 p1.speed *= elasticity p2.speed *= elasticity overlap = 0.5 * (p1.size + p2.size - dist + 1) p1.x += math.sin(angle) * overlap p1.y -= math.cos(angle) * overlap p2.x -= math.sin(angle) * overlap p2.y += math.cos(angle) * overlap ### VIBRATION if VIBRATE and p1.vibrate and p2.vibrate: if android: android.vibrate(0.05) if SOUND and p1.sound and p2.sound: if p1.hitpoints <= 0 or p2.hitpoints <= 0: DEATH_SOUND.play() if not mixer.get_busy(): vol = float((total_speed * 2) / 100) if vol > 100: vol = 100 BOP_SOUND.set_volume(vol) BOP_SOUND.play()
def play_next_song(): song = SONG_PATH + song_list[current_index] print("Index: " + str(current_index)) print("Playing: " + song) sound = mixer.Sound(file=song) sound.play() while mixer.get_busy(): pass # Fix for small song. If default song of "ding" is biggest than custom song if sound.get_length() < MIN_SOUND_TIME: print("Original song not finish, waiting " + str(MIN_SOUND_TIME - sound.get_length()) + "s more") time.sleep(MIN_SOUND_TIME - sound.get_length()) update_index()
def wait(self): """<DOC> Blocks until the sound has finished playing or returns right away if no # sound is playing. Example: >>> from openexp.sampler import sampler >>> src = exp.get_file('my_sound.ogg') >>> my_sampler = sampler(exp, src) >>> my_sampler.play() >>> my_sampler.wait() >>> print 'The sampler is finished!' </DOC>""" while mixer.get_busy(): pass
def notifier(dt,eLists=myLists,loud=True): global allMail global newMail print "notify" if mixer.get_busy()==False: print "not busy" playMessage=False for e in eLists: try: mails=get_mail('Walconiator','fuckthisshit7', e) except: print "auth error" mails=[] for mail in mails: allMail.insert(0,mail) newMail.insert(0,mail)
def play(str) : mixer.init() long_sound = mixer.Sound("beep500.wav") short_sound = mixer.Sound("beep200.wav") for char in str : while mixer.get_busy() : time.sleep(0.1) if char == '-' : long_sound.play() elif char == '.' : short_sound.play() elif char == ' ' : time.sleep(0.5)
def on_touch_up(self, touch): if self.value > 0: # If the sound is not playing, start it if not mixer.get_busy(): self.rain.play(loops=-1) self.rain.set_volume(self.value) else: self.rain.fadeout(2000) return True
def get(self): parser = reqparse.RequestParser() parser.add_argument( 'song', type=str) # looks for the argument holding song name parser.add_argument( 'function', type=str) # looks for the argument holding function args = parser.parse_args() print args # if song is not in queue doesn't crash try: print m.queue[0] m.playsong(m.queue[0]) except: m.decode(args['function'], args['song']) if mixer.get_busy() == True: m.playnext() return
def start_player(self): mixer.init() rospy.loginfo("busy initializing player") last_played = '' # Main loop rate = rospy.Rate(10) rospy.loginfo("Spinning at 10Hz") while not rospy.is_shutdown(): self.busy = False rospy.loginfo("Audio player ready, new file: '" + self.new_file + "' last file played: '" + last_played + "' extension:" + self.file_extention) # check if the command has been played if ((self.new_file != last_played) & (self.new_file != self.no_file)): last_played = self.new_file rospy.loginfo("File different from previous\n") file_full_name = self.file_path + self.new_file + self.file_extention # check if it exist, else select a default file to play if os.path.isfile(file_full_name): rospy.loginfo("Audio file found\n") else: file_full_name = self.file_path + self.default_file + self.file_extention rospy.loginfo("Audio file not found\n") # load and play file print(self.file_extention) print(file_full_name) s = mixer.Sound(file_full_name) rospy.loginfo("Audio file loaded\n") # mixer.Sound.play(s) s.play(loops=0, maxtime=0, fade_ms=0) rospy.loginfo("Audio file played\n") # wait for file to finish while mixer.get_busy(): # pygame.time.Clock().tick(10) rospy.loginfo("Playing audio file\n") self.busy = True self.publish_result() self.publish_result() rate.sleep() mixer.quit()
def wait(self): """<DOC> Blocks until the sound has finished playing or returns right away if no # sound is playing. Example: >>> from openexp.sampler import sampler >>> src = exp.get_file('my_sound.ogg') >>> my_sampler = sampler(exp, src) >>> my_sampler.play() >>> my_sampler.wait() >>> print('The sampler is finished!') </DOC>""" while mixer.get_busy(): self.keyboard.flush()
def is_playing(self): """<DOC> Checks if a sound is currently playing. Returns: True if a sound is playing, False if not. Example: >>> from openexp.sampler import sampler >>> src = exp.get_file('my_sound.ogg') >>> my_sampler = sampler(exp, src) >>> my_sampler.play() >>> self.sleep(100) >>> if my_sampler.is_playing(): >>> print 'The sampler is still playing!' </DOC>""" return bool(mixer.get_busy())
def collide(p1, p2): """ Tests whether two particles overlap If they do, make them bounce, i.e. update their angle, speed and position """ dx = p1.x - p2.x dy = p1.y - p2.y dist = math.hypot(dx, dy) if dist < p1.size + p2.size: angle = math.atan2(dy, dx) + 0.5 * math.pi if p1.mass == p2.mass: p1.mass += 1 total_mass = p1.mass + p2.mass (p1angle, p1speed) = addVectors((p1.angle, p1.speed*(p1.mass-p2.mass)/total_mass), (angle, 2*p2.speed*p2.mass/total_mass)) (p2angle, p2speed) = addVectors((p2.angle, p2.speed*(p2.mass-p1.mass)/total_mass), (angle+math.pi, 2*p1.speed*p1.mass/total_mass)) (p2.angle, p2.speed, p1.angle, p1.speed) = (p2angle, p2speed, p1angle, p1speed) elasticity = p2.elasticity * p1.elasticity total_speed = (p1.speed + p2.speed) p1.hitpoints -= elasticity*2 p2.hitpoints -= elasticity*2 p1.speed *= elasticity p2.speed *= elasticity overlap = 0.5*(p1.size + p2.size - dist+1) p1.x += math.sin(angle)*overlap p1.y -= math.cos(angle)*overlap p2.x -= math.sin(angle)*overlap p2.y += math.cos(angle)*overlap ### VIBRATION if VIBRATE and p1.vibrate and p2.vibrate: if android: android.vibrate(0.05) if SOUND and p1.sound and p2.sound: if p1.hitpoints <= 0 or p2.hitpoints <= 0: DEATH_SOUND.play() if not mixer.get_busy(): vol = float((total_speed*2)/100) if vol > 100: vol = 100 BOP_SOUND.set_volume(vol) BOP_SOUND.play()
def is_playing(self): """<DOC> Checks if a sound is currently playing. Returns: True if a sound is playing, False if not. Example: >>> from openexp.sampler import sampler >>> src = exp.get_file('my_sound.ogg') >>> my_sampler = sampler(exp, src) >>> my_sampler.play() >>> self.sleep(100) >>> if my_sampler.is_playing(): >>> print('The sampler is still playing!') </DOC>""" return bool(mixer.get_busy())
def doorbell_pressed(self, test=False, test_string=''): print("Doorbell pressed.") if self.silenced == False: # play the ding sound file if mixer.get_busy() == True: mixer.stop() # end if self.play_sound("ding") # end if # time format = string # format = 2018-01-13 08:48:00 if (test == False): message = {"timestamp": self.get_time(), "status": "HIGH"} else: message = {"timestamp": self.get_time(), "status": test_string} # end if self.publish_message(message)
def play_file(page=None, gender='f'): d = [] if page == PageOne: d.append(mixer.Sound(sounds_path + 'intor0_1.wav')) d.append(mixer.Sound(sounds_path + 'intro0_2.wav')) d.append(mixer.Sound(sounds_path + 'intro0_3%s.wav' % gender)) d.append(mixer.Sound(sounds_path + 'rate.wav')) elif page == PageTwo: d.append(mixer.Sound(sounds_path + 'suspect_c_and_d_intro.wav')) elif page == PageThree: d.append(mixer.Sound(sounds_path + 'rate.wav')) elif page == PageFour: d.append(mixer.Sound(sounds_path + 'suspect_b_and_d_intro.wav')) elif page == PageSix: d.append(mixer.Sound(sounds_path + 'who_did_it.wav')) elif page == PageSeven: d.append(mixer.Sound(sounds_path + 'hire_%s.wav' % gender)) for i in d: while mixer.get_busy(): pass i.play()
def play(self, event): from pygame import mixer if not mixer.get_init(): mixer.init() if mixer.get_busy() and self.sound: self.sound.stop() return volume_attr = self.aguidata.get('volume') if volume_attr: volume = getattr(self.window.object, volume_attr) else: volume = 1 try: sound = get_sound(self.get_control_value(), volume=volume) sound.play() self.sound = sound except: self.sound = None self.play_button_down = True self.looping = False wx.CallLater(0.1, self.test_button) event.Skip()
def polly_say(text): os.environ["AWS_PROFILE"] = "soundboard-polly" client = boto3.client('polly', 'eu-central-1') response = client.synthesize_speech(OutputFormat='mp3', Text=text, VoiceId='Brian') if "AudioStream" in response: file_name = "polly_audio_%s.mp3" % uuid.uuid4() pf = open(file_name, "wb") audiostream = response["AudioStream"] with closing(audiostream): data = audiostream.read() pf.write(data) pf.flush() pf.close() mixer.music.load(file_name) mixer.music.play() while mixer.get_busy(): sleep(0.1) os.remove(file_name)
def play(self, event): from pygame import mixer if not mixer.get_init(): mixer.init() if mixer.get_busy() and self.sound: self.sound.stop() return volume_attr = self.aguidata.get("volume") if volume_attr: volume = getattr(self.window.object, volume_attr) else: volume = 1 try: sound = get_sound(self.get_control_value(), volume=volume) sound.play() self.sound = sound except: self.sound = None self.play_button_down = True self.looping = False wx.CallLater(0.1, self.test_button) event.Skip()
def play_file_art(page=None, gender='f'): d = [] if page == artOne: d.append(mixer.Sound(sounds_path + 'art_intro_0.wav')) d.append(mixer.Sound(sounds_path + 'art_intro_1_%s.wav' % gender)) d.append(mixer.Sound(sounds_path + 'rate_art.wav')) elif page == artTwo: d.append(mixer.Sound(sounds_path + 'caught_young.wav')) elif page == artThree: d.append(mixer.Sound(sounds_path + 'rate_art.wav')) elif page == artFour: d.append(mixer.Sound(sounds_path + 'most_expensive.wav')) elif page == artFive: d.append(mixer.Sound(sounds_path + 'rank_all_9.wav')) elif page == artSix: d.append(mixer.Sound(sounds_path + 'what_was_most_expensive_piece.wav')) elif page == artSeven: d.append(mixer.Sound(sounds_path + 'robot_art_buyer_%s.wav' % gender)) for i in d: while mixer.get_busy(): pass i.play()
def expt4(): print '-------------------------' print 'Demo 2: Brain music' raw_input('This demo will record your brain signal for 15s and ' + 'play it back at 2x time speed (so you can hear it). \n' \ 'Hit enter to start.') data, blinks = startEEG(15, music=True) print 'One moment, playing your brain music...\n' mixer.quit() mixer.init(frequency=1024, size=-16, channels=1, buffer=4096) soundVals = [] file = open("brain_music.raw", 'r') for line in file: soundVals.append(int(line.rstrip('\n').split(',')[1])) file.close() soundVals = array(soundVals) sound = sndarray.make_sound(soundVals) mixer.Sound.play(sound) while mixer.get_busy(): time.sleep(1) mixer.quit() raw_input('Hit enter to continue...') print('\n\n')
def playSound(soundfile, blocking = True): """Play sound through default mixer channel in blocking manner. This will load the whole sound into memory before playback """ if not os.path.exists(soundfile): print(("Sound file " + soundfile + " doesn't exists.")) return if blocking: print(("Starting playback " + soundfile + " blocking")) else: print(("Starting playback " + soundfile)) sound = mixer.Sound(soundfile) clock = pygame.time.Clock() sound.play() if blocking: while mixer.get_busy(): for event in pygame.event.get(): pass print("Playback Finished.")
def expt4(): print '-------------------------' print 'Demo 2: Brain music' raw_input('This demo will record your brain signal for 15s and ' + 'play it back at 2x time speed (so you can hear it). \n' \ 'Hit enter to start.') data, blinks=startEEG(15, music=True) print 'One moment, playing your brain music...\n' mixer.quit() mixer.init(frequency=1024, size=-16, channels=1, buffer=4096) soundVals = [] file = open("brain_music.raw",'r') for line in file: soundVals.append(int(line.rstrip('\n').split(',')[1])) file.close() soundVals = array(soundVals) sound = sndarray.make_sound(soundVals) mixer.Sound.play(sound) while mixer.get_busy(): time.sleep(1) mixer.quit() raw_input('Hit enter to continue...') print('\n\n')
"B1": 44, "C2": 42, "#C2": 39, "D2": 37, "#D2": 35, "E2": 33, "F2": 31, "#F2": 29, "G2": 28, "#G2": 26, "A2": 25, "#A2": 23, "B2": 22, "C3": 21, "-": 0 } jgm = "4C2 4D2 4E2 4E2 4E2 4E2 4E2 4E2 2E2 4E2 4E2 4D2 4E2 2F2 2E2 4E2 4E2 2D2 4D2 4d2 4b1 4d2 1c2 2c2 2g2 4g2 2g2 4g2 4g2 4g2 2g2 4g2 4g2 4f2 4a2 2g2 2F2 4f2 4f2 2e2 4e2 4e2 4d2 4f2 1e2 2e2 2E2 4e2 4e2 2e2 4e2 4e2 4g2 4g2 2g2 4f2 4f2 2f2 2e2 4e2 4e2 4d2 4d2 4d2 4d2 4b1 4d2 1c2 2c2 4C3 4b2 1c3 2c3 4b2 4a2 1b2 2b2 4a2 4g2 1a2 1a2 4c2 4c2 4d2 4d2 4e2 4e2 4d2 4e2 1f2" mytune = jgm mytune = mytune.replace(',', ' ') mytune = mytune.split() if __name__ == "__main__": t = find_tune(mytune) t.play() running = True while running: running = mix.get_busy()
def play(self, soundObject): if not mixer.get_busy(): soundObject.play()
def main(arraytype=None): """play various sndarray effects If arraytype is provided then use that array package. Valid values are 'numeric' or 'numpy'. Otherwise default to NumPy, or fall back on Numeric if NumPy is not installed. """ main_dir = os.path.split(os.path.abspath(__file__))[0] if arraytype not in ("numpy", None): raise ValueError("Array type not supported: %r" % arraytype) print("Using %s array package" % sndarray.get_arraytype()) print("mixer.get_init %s" % (mixer.get_init(),)) samples_per_second = pygame.mixer.get_init()[0] print(("-" * 30) + "\n") print("loading sound") sound = mixer.Sound(os.path.join(main_dir, "data", "car_door.wav")) print("-" * 30) print("start positions") print("-" * 30) start_pos = 0.1 sound2 = sound_from_pos(sound, start_pos, samples_per_second) print("sound.get_length %s" % (sound.get_length(),)) print("sound2.get_length %s" % (sound2.get_length(),)) sound2.play() while mixer.get_busy(): pygame.time.wait(200) print("waiting 2 seconds") pygame.time.wait(2000) print("playing original sound") sound.play() while mixer.get_busy(): pygame.time.wait(200) print("waiting 2 seconds") pygame.time.wait(2000) # if 0: # #TODO: this is broken. # print (("-" * 30) + "\n") # print ("Slow down the original sound.") # rate = 0.2 # slowed_sound = slow_down_sound(sound, rate) # slowed_sound.play() # while mixer.get_busy(): # pygame.time.wait(200) print("-" * 30) print("echoing") print("-" * 30) t1 = time.time() sound2 = make_echo(sound, samples_per_second) print("time to make echo %i" % (time.time() - t1,)) print("original sound") sound.play() while mixer.get_busy(): pygame.time.wait(200) print("echoed sound") sound2.play() while mixer.get_busy(): pygame.time.wait(200) sound = mixer.Sound(os.path.join(main_dir, "data", "secosmic_lo.wav")) t1 = time.time() sound3 = make_echo(sound, samples_per_second) print("time to make echo %i" % (time.time() - t1,)) print("original sound") sound.play() while mixer.get_busy(): pygame.time.wait(200) print("echoed sound") sound3.play() while mixer.get_busy(): pygame.time.wait(200)
def wait(self): while mixer.get_busy(): self.keyboard.flush()
GPIO.setup(IR_PIN, GPIO.OUT) # Initialize pygame mixer mixer.init() # Remember the current and previous button states current_state = True prev_state = True # Load the sounds sound = mixer.Sound("applause-1.wav") # If button is pushed, light up LED try: while True: current_state = GPIO.input(btn_pin) print(current_state) if (current_state == False) and (prev_state == True): if mixer.get_busy(): mixer.stop() sound.play() GPIO.output(IR_PIN, GPIO.HIGH) if not mixer.get_busy(): GPIO.output(IR_PIN, GPIO.LOW) prev_state = current_state # When you press ctrl+c, this will be called finally: mixer.quit() GPIO.cleanup()
def make_noise(): sound.play() while mixer.get_busy(): sleep(1)
def PlayBlocking(fn): mixer.Sound(fn).play() while mixer.get_busy(): pass
def beep(freq, duration): samples = (sin(arrayrange(duration/1000.0 * samplerate) * (2 * pi * (freq / samplerate))) * float(1 << (bits - 2))).astype(Int16) snd = sndarray.make_sound(samples) snd.play() while mixer.get_busy(): pass
def play(sound): """Play a sound and wait for it to finish.""" sound.play() while mixer.get_busy(): time.wait(10)
def isTalking(self): return mixer.get_busy()
def busy(): """ Is the mixer busy? """ return (not loop_sound[0] and not loop_sound[1] and not loop_sound[2] and not loop_sound[3]) and mixer.get_busy()
def main(arraytype=None): """play various sndarray effects If arraytype is provided then use that array package. Valid values are 'numeric' or 'numpy'. Otherwise default to NumPy, or fall back on Numeric if NumPy is not installed. """ main_dir = os.path.split(os.path.abspath(__file__))[0] if arraytype not in ('numpy', None): raise ValueError('Array type not supported: %r' % arraytype) print ("Using %s array package" % sndarray.get_arraytype()) print ("mixer.get_init %s" % (mixer.get_init(),)) inited = mixer.get_init() samples_per_second = pygame.mixer.get_init()[0] print (("-" * 30) + "\n") print ("loading sound") sound = mixer.Sound(os.path.join(main_dir, 'data', 'car_door.wav')) print ("-" * 30) print ("start positions") print ("-" * 30) start_pos = 0.1 sound2 = sound_from_pos(sound, start_pos, samples_per_second) print ("sound.get_length %s" % (sound.get_length(),)) print ("sound2.get_length %s" % (sound2.get_length(),)) sound2.play() while mixer.get_busy(): pygame.time.wait(200) print ("waiting 2 seconds") pygame.time.wait(2000) print ("playing original sound") sound.play() while mixer.get_busy(): pygame.time.wait(200) print ("waiting 2 seconds") pygame.time.wait(2000) if 0: #TODO: this is broken. print (("-" * 30) + "\n") print ("Slow down the original sound.") rate = 0.2 slowed_sound = slow_down_sound(sound, rate) slowed_sound.play() while mixer.get_busy(): pygame.time.wait(200) print ("-" * 30) print ("echoing") print ("-" * 30) t1 = time.time() sound2 = make_echo(sound, samples_per_second) print ("time to make echo %i" % (time.time() - t1,)) print ("original sound") sound.play() while mixer.get_busy(): pygame.time.wait(200) print ("echoed sound") sound2.play() while mixer.get_busy(): pygame.time.wait(200) sound = mixer.Sound(os.path.join(main_dir, 'data', 'secosmic_lo.wav')) t1 = time.time() sound3 = make_echo(sound, samples_per_second) print ("time to make echo %i" % (time.time() - t1,)) print ("original sound") sound.play() while mixer.get_busy(): pygame.time.wait(200) print ("echoed sound") sound3.play() while mixer.get_busy(): pygame.time.wait(200)
def is_playing(self): return bool(mixer.get_busy())