Esempio n. 1
0
 def submit(self):
     self.submit_button.configure(state=DISABLED)
     self.play_button.configure(state=DISABLED)
     for item in self.stuff_to_disable:
         item.configure(state=DISABLED)
     
     try:
         mixer.quit()
     except error: # pygame.error
         pass # music was never played, so we can't stop it
     
     right = 0
     wrong = []
     
     excerpt = "A"
     for piece in self.order:
         questions = self.questions[piece].keys()
         questions.reverse() # correct question ordering
         for question in questions:
             correct_answer = config.get(piece, question)
             given_answer = self.answers[piece][question].get()
             if given_answer == u"Der Erlk\xf6nig": # unicode bugfix
                 given_answer = "Der Erlk\xc3\xb6nig"
             if correct_answer == given_answer:
                 right += 1
             else:
                 wrong.append((excerpt, config.get(piece, "title"),
                         question, given_answer, correct_answer))
         excerpt = chr(ord(excerpt) + 1)
     
     results = Toplevel() # make a new window to display results
     results.title("Results")
     
     noq = self.number_of_questions
     text = "{0} of {1} answered correctly ({2}%):".format(right, noq,
             round((right / noq) * 100, 2))
     
     if right == noq:
         text += "\n\nCongratulations, you got everything right!"
     
     else:
         text += "\n"
         for excerpt, title, question, given_answer, correct_answer in wrong:
             if not given_answer:
                 if question == "title":
                     text += "\nYou left the title of Excerpt {0} blank; it's \"{1}\".".format(
                             excerpt, correct_answer)
                 else:
                     text += "\nYou left the {0} of \"{1}\" blank; it's {2}.".format(
                             question, title, correct_answer)
             elif question == "title":
                 text += "\nExcerpt {0} was {1}, not {2}.".format(
                         excerpt, correct_answer, given_answer)
             else:
                 text += "\nThe {0} of \"{1}\" is {2}, not {3}.".format(
                         question, title, correct_answer, given_answer)
         
     label = Label(results, text=text, justify=LEFT, padx=15, pady=10,
             font=Font(family="Verdana", size=8))
     label.pack()
Esempio n. 2
0
def monitor_up(join, tic, name):

    data = []
    spin = 100000000
    numy = 0
    mixer.init()
    mixer.quit()
    start_level = waves(join, name)

    while True:
        numy += 1
        base_level = waves(join, name)

        if (base_level * 0.75) > start_level:
            break

        if spin > base_level:
            music_played = cycle(join, name)
            music_level = music_played[1]
            music_number = music_played[0]

            if music_level > base_level:
                play_func(music_number)
                data += [[
                    "rot:{}".format(numy), "sound: {}".format(music_number)
                ]]
            else:
                data += [["rot:{}".format(numy), "no switch"]]

            spin = music_level
        time.sleep(tic)

    return (data)
Esempio n. 3
0
def playBell(name, t):
    mixer.init()
    print name
    sound = mixer.Sound(name)
    sound.play()
    time.sleep(t)
    mixer.quit()
Esempio n. 4
0
    def test_get_raw_more(self):
        """ test the array interface a bit better.
        """
        import platform
        IS_PYPY = 'PyPy' == platform.python_implementation()

        if IS_PYPY:
            return
        from ctypes import pythonapi, c_void_p, py_object

        try:
            Bytes_FromString = pythonapi.PyBytes_FromString
        except:
            Bytes_FromString = pythonapi.PyString_FromString
        Bytes_FromString.restype = c_void_p
        Bytes_FromString.argtypes = [py_object]
        mixer.init()
        try:
            samples = as_bytes('abcdefgh') # keep byte size a multiple of 4
            snd = mixer.Sound(buffer=samples)
            raw = snd.get_raw()
            self.assertTrue(isinstance(raw, bytes_))
            self.assertNotEqual(snd._samples_address, Bytes_FromString(samples))
            self.assertEqual(raw, samples)
        finally:
            mixer.quit()
Esempio n. 5
0
    def test_get_init__returns_exact_values_used_for_init(self):
        return 
        # fix in 1.9 - I think it's a SDL_mixer bug.

        # TODO: When this bug is fixed, testing through every combination
        #       will be too slow so adjust as necessary, at the moment it
        #       breaks the loop after first failure

        configs = []
        for f in FREQUENCIES:
            for s in SIZES:
                for c in CHANNELS:
                    configs.append ((f,s,c))

        print (configs)
    

        for init_conf in configs:
            print (init_conf)
            f,s,c = init_conf
            if (f,s) == (22050,16):continue
            mixer.init(f,s,c)

            mixer_conf = mixer.get_init()
            import time
            time.sleep(0.1)

            mixer.quit()
            time.sleep(0.1)

            if init_conf != mixer_conf:
                continue
            self.assertEquals(init_conf, mixer_conf)
Esempio n. 6
0
    def test_get_raw_more(self):
        """ test the array interface a bit better.
        """
        import platform
        IS_PYPY = 'PyPy' == platform.python_implementation()

        if IS_PYPY:
            return
        from ctypes import pythonapi, c_void_p, py_object

        try:
            Bytes_FromString = pythonapi.PyBytes_FromString
        except:
            Bytes_FromString = pythonapi.PyString_FromString
        Bytes_FromString.restype = c_void_p
        Bytes_FromString.argtypes = [py_object]
        mixer.init()
        try:
            samples = as_bytes('abcdefgh') # keep byte size a multiple of 4
            snd = mixer.Sound(buffer=samples)
            raw = snd.get_raw()
            self.assertTrue(isinstance(raw, bytes_))
            self.assertNotEqual(snd._samples_address, Bytes_FromString(samples))
            self.assertEqual(raw, samples)
        finally:
            mixer.quit()
Esempio n. 7
0
    def todo_test_pre_init__keyword_args(self):
        # Fails on Mac; probably older SDL_mixer
## Probably don't need to be so exhaustive. Besides being slow the repeated
## init/quit calls may be causing problems on the Mac.
##        configs = ( {'frequency' : f, 'size' : s, 'channels': c }
##                    for f in FREQUENCIES
##                    for s in SIZES
##                    for c in CHANNELS )
        configs = [{'frequency' : 44100, 'size' : 16, 'channels' : 1}]

        for kw_conf in configs:
            mixer.pre_init(**kw_conf)
            mixer.init()

            mixer_conf = mixer.get_init()
            
            self.assertEquals(
                # Not all "sizes" are supported on all systems.
                (mixer_conf[0], abs(mixer_conf[1]), mixer_conf[2]),
                (kw_conf['frequency'],
                 abs(kw_conf['size']),
                 kw_conf['channels'])
            )
            
            mixer.quit()
Esempio n. 8
0
def polly(message, voicename):
    # connect the polly to be communicating with AWS
    polly = boto3.client('polly',
                         region_name='us-west-2',
                         aws_access_key_id='<your_aws_access_key>',
                         aws_secret_access_key='<your_aws_secret_key>')
    # specify the voice and output the voice text
    if message == '':
        message = "Hello! My name is " + voicename + '.......'
    spoken_text = polly.synthesize_speech(Text=message,
                                          OutputFormat='mp3',
                                          VoiceId=voicename)

    lcd.text(message, 1)

    #write the audio file, and open for playing the mp3
    with open('/home/pi/output.mp3', 'wb') as f:
        f.write(spoken_text['AudioStream'].read())
        f.close()

    mixer.init()
    mixer.music.load('/home/pi/output.mp3')  # prepare the mp3 file
    mixer.music.play()  # play the mp3

    # check if the music player is working
    while mixer.music.get_busy() == True:
        pass

    mixer.quit()
    lcd.clear()  # clear the LCD screen
def check_condition(code, que):
    """
    This will ask user wheather activity is completed or not and if completed will stop music
    :param code: Key word to stop already running alarm
    :param que: Question to be asked to user about activity
    :return: none
    """
    while True:
        global keyword
        codevar = input(f"Had you {que} ? Enter 'Done' if completed: ").upper()
        if codevar == code:
            stop_music()
            init(autoreset=True)
            print(Fore.LIGHTGREEN_EX + "Very Good.")
            keyword = ""
            break
        elif codevar == "EXIT":
            keyword = "EXIT"
            mixer.music.stop()
            mixer.quit()
            init(autoreset=True)
            print(Fore.LIGHTRED_EX + "\nTimer Stoped.")
            break
        else:
            init(autoreset=True)
            print(Fore.LIGHTBLUE_EX + "\nWhat did you said?\nI'm unable to understand that.")
Esempio n. 10
0
def monitor_down(join, tic, name):

    data = []
    spin = 0
    numy = 0
    mixer.init()
    mixer.quit()
    start_level = waves(join, name)

    while True:
        numy += 1
        base_level = waves(join, name)

        if (base_level * 1.25) < start_level:
            break

        if spin < base_level:
            music_played = cycle(join, name)
            music_level = music_played[1]
            music_number = music_played[0]

            if music_level < base_level:
                play_func(music_number)
                data += [
                    music_number, "rot:{}".format(numy),
                    "sound: {}".format(music_number)
                ]
            else:
                data += ["no switch", "rot:{}".format(numy)]

            spin = music_level
        time.sleep(tic)

    return (data)
Esempio n. 11
0
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
Esempio n. 12
0
def urll():
    urldata = "https://musicplayer119.herokuapp.com/index1.txt"
    now = datetime.now()
    urll.EqWebUrl = requests.get(urldata)
    urll.data = urll.EqWebUrl.text

    if urll.EqWebUrl.status_code == 200:
        print("Connected to Remote!")
    print(urll.data)

    if urll.EqWebUrl.status_code != 200:
        print("Bad Connection!")

    if urll.data == 'Com':
        # music()\
        #winsound.Beep(600,5000)
        #winsound.Beep(200,1000)
        #os.system('newPY.py')
        #print('newPY.py')
        music()

    if urll.data == 'Stop':
        mixer.quit()
        print("Song Stopped")
    if urll.data == 'Play':
        print("Song Playing")
        print(now)

    sleep(2)
    urll()
Esempio n. 13
0
def simulation_loop(main_surface, game_clock, settings):
    frame_resolution = settings.frame_resolution
    game_frame_rate = settings.frame_rate
    camera = Camera(frame_resolution, settings.map_size)
    entity_master = EntityMaster(initial_hives=settings.initial_hives,
                                 default_bees_per_hive=settings.initial_bees_per_hive,
                                 play_area_dimensions=settings.map_size,
                                 flower_spawn_strategy=settings.flower_spawn_strategy,
                                 hive_spawn_strategy=settings.hive_spawn_strategy,
                                 flower_num=settings.flower_num)
    gui_master = GuiMaster(frame_resolution, entity_master, game_clock)
    # Init Music
    if settings.play_music:
        mixer.init()
        mixer.music.load(join('source', 'assets', 'sounds', 'bee_music.mp3'))
        mixer.music.play(loops=-1, start=0.0)

    # Main Game Loop
    while True:
        time_delta = game_clock.tick(game_frame_rate) / 1000.0
        gui_master.update(time_delta)
        camera.render(entity_master.get_entities(), main_surface)
        gui_master.draw_ui(main_surface)
        display.flip()

        for e in event.get():
            if e.type == QUIT:
                quit()
                exit()
            output = gui_master.process_events(e, camera)

            if output == 0:
                mixer.quit()
                return output
Esempio n. 14
0
def naver_say(text):

    client_id = ""
    client_secret = ""
    encText = urllib.parse.quote(text)
    data = "speaker=mijin&speed=0&text=" + encText
    url = "https://naveropenapi.apigw.ntruss.com/voice/v1/tts"

    request = urllib.request.Request(url)
    request.add_header("X-NCP-APIGW-API-KEY-ID", client_id)
    request.add_header("X-NCP-APIGW-API-KEY", client_secret)
    response = urllib.request.urlopen(request, data=data.encode('utf-8'))
    rescode = response.getcode()

    if (rescode == 200):
        response_body = response.read()
        with open('naver.mp3', 'wb') as f:
            f.write(response_body)

        mixer.init(frequency=16000)
        mixer.music.load('naver.mp3')
        mixer.music.play()
        while mixer.music.get_busy():
            time.sleep(1)
        mixer.quit()
    else:
        print("Error Code:" + rescode)
Esempio n. 15
0
    def playById(self, song_id: int):
        #Reset previous playing itemTV
        if len(self.__songs_previous_id):
            self.tag_configure(self.__song_playing_id,
                               image=self.imgs["none"],
                               foreground=config.colors["TV_FG"])

        song = self.getSongById(song_id)

        #pygame.mixer does not support different frequencies
        if mixer.get_init()[0] != song.getFrequency():
            mixer.quit()
            mixer.init(frequency=song.getFrequency(), channels=2)

        mixer.music.load(song.path)
        mixer.music.play()
        self.__is_load = True

        self.__song_playing_id = song_id
        self.tag_configure(self.__song_playing_id,
                           image=self.imgs["playing"],
                           foreground=config.colors["TV_FG_PLAYING"])

        #Push to "self.__songs_previous_id" if it is the first song or it is not the previous song
        if (not len(self.__songs_previous_id)) or (
                song_id != self.__songs_previous_id[-1]):
            self.__songs_previous_id.append(song_id)
Esempio n. 16
0
    def test_get_init__returns_exact_values_used_for_init(self):
        return 
        # fix in 1.9 - I think it's a SDL_mixer bug.

        # TODO: When this bug is fixed, testing through every combination
        #       will be too slow so adjust as necessary, at the moment it
        #       breaks the loop after first failure

        configs = []
        for f in FREQUENCIES:
            for s in SIZES:
                for c in CHANNELS:
                    configs.append ((f,s,c))

        print (configs)
    

        for init_conf in configs:
            print (init_conf)
            f,s,c = init_conf
            if (f,s) == (22050,16):continue
            mixer.init(f,s,c)

            mixer_conf = mixer.get_init()
            import time
            time.sleep(0.1)

            mixer.quit()
            time.sleep(0.1)

            if init_conf != mixer_conf:
                continue
            self.assertEquals(init_conf, mixer_conf)
Esempio n. 17
0
 def playSound(self):
    #spielt einen Sound ab
    try:
        CHUNK = 1024;
        wf = wave.open(self.newName, 'rb')
        p = pyaudio.PyAudio()
        stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                        channels=wf.getnchannels(),
                        rate=wf.getframerate(),
                        output=True)
        data = wf.readframes(CHUNK)          
        while data != '':
            stream.write(data)
            data = wf.readframes(CHUNK)
        stream.stop_stream()
        stream.close()            
        p.terminate()
    except:
        mixer.init()
        mixer.music.load(self.newName)
        mixer.music.play(1,0.0)
        while mixer.music.get_busy():
            pass
        mixer.quit()           
    return 	
Esempio n. 18
0
    def test_sound__before_init(self):
        """Ensure exception raised for Sound() creation with non-init mixer."""
        mixer.quit()
        filename = example_path(os.path.join('data', 'house_lo.wav'))

        with self.assertRaisesRegex(pygame.error, 'mixer not initialized'):
            mixer.Sound(file=filename)
Esempio n. 19
0
    def todo_test_pre_init__keyword_args(self):
        # Fails on Mac; probably older SDL_mixer
## Probably don't need to be so exhaustive. Besides being slow the repeated
## init/quit calls may be causing problems on the Mac.
##        configs = ( {'frequency' : f, 'size' : s, 'channels': c }
##                    for f in FREQUENCIES
##                    for s in SIZES
##                    for c in CHANNELS )
        configs = [{'frequency' : 44100, 'size' : 16, 'channels' : 1}]

        for kw_conf in configs:
            mixer.pre_init(**kw_conf)
            mixer.init()

            mixer_conf = mixer.get_init()
            
            self.assertEquals(
                # Not all "sizes" are supported on all systems.
                (mixer_conf[0], abs(mixer_conf[1]), mixer_conf[2]),
                (kw_conf['frequency'],
                 abs(kw_conf['size']),
                 kw_conf['channels'])
            )
            
            mixer.quit()
Esempio n. 20
0
def cleanup():
    logger.info("Flush queue")
    with _q_lock:
        _events = []
    print "Cleanup IO"
    GPIO.cleanup()  # cleanup all GPIO
    mixer.quit()
 def Write(self, cuadruplo):
     op = cuadruplo[0]
     value = str(self.getValue(cuadruplo[1]))
     if op == 16:
         print(value)
     elif op == 17:
         #Generación del archivo .mp3
         tts = gTTS(text= value, lang='es')
         tts.save('speech.mp3')
         #Carga el archivo .mp3 a memoria
         with open('speech.mp3') as f: 
             PlayedMp3File = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) 
         #Enciende el mixer
         mixer.init()
         #carga el audio al mixer
         mixer.music.load(PlayedMp3File)
         #Reproduce el audio
         mixer.music.play()
         #Mientras el audio se esta reproduciendo espera
         while mixer.music.get_busy() == True:
             continue
         #Cierra el archivo .mp3
         PlayedMp3File.close()
         #Apaga el mixer
         mixer.quit()
         #Si el archivo existe borralo
         if os.path.exists('speech.mp3'):
             os.remove('speech.mp3')
     elif op == 18:
         intab = ' !#$%&"()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_abcdefghijklmnopqrstuvwxyz'
         outtab = ' ⠮⠼⠫⠩⠯⠄⠷⠾⠡⠬⠠⠤⠨⠌⠴⠂⠆⠒⠲⠢⠖⠶⠦⠔⠱⠰⠣⠿⠜⠹⠈⠁⠃⠉⠙⠑⠋⠛⠓⠊⠚⠅⠇⠍⠝⠕⠏⠟⠗⠎⠞⠥⠧⠺⠭⠽⠵⠪⠳⠻⠘⠸⠁⠃⠉⠙⠑⠋⠛⠓⠊⠚⠅⠇⠍⠝⠕⠏⠟⠗⠎⠞⠥⠧⠺⠭⠽⠵'
         transtab = str.maketrans(intab, outtab)
         print(value.translate(transtab))
Esempio n. 22
0
 def play_song(self):
     mixer.quit()  #it stop the current song
     mixer.init(
         frequency=self.audio_tag.info.sample_rate
     )  #mixer is for the wave frequency so we have to give the frequency of song
     mixer.music.load(self.song_path)
     mixer.music.play()
Esempio n. 23
0
def TextToSpeech():
    console.delete(1.0, END)
    console.insert(END, 'Reproduciendo Audio')

    toBraille = codeArea.get("1.0",'end-1c')
    intab = ' ⠮⠼⠫⠩⠯⠄⠷⠾⠡⠬⠠⠤⠨⠌⠴⠂⠆⠒⠲⠢⠖⠶⠦⠔⠱⠰⠣⠿⠜⠹⠈⠁⠃⠉⠙⠑⠋⠛⠓⠊⠚⠅⠇⠍⠝⠕⠏⠟⠗⠎⠞⠥⠧⠺⠭⠽⠵⠪⠳⠻⠘⠸⠁⠃⠉⠙⠑⠋⠛⠓⠊⠚⠅⠇⠍⠝⠕⠏⠟⠗⠎⠞⠥⠧⠺⠭⠽⠵'
    outtab = ' !#$%&"()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_abcdefghijklmnopqrstuvwxyz'
    transtab = str.maketrans(intab, outtab)
    toSpeech = toBraille.translate(transtab)
    
    tts = gTTS(text= toSpeech, lang='es')
    tts.save('speech.mp3')

    with open('speech.mp3') as f: 
        PlayedMp3File = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) 

    mixer.init()
    mixer.music.load(PlayedMp3File)
    mixer.music.play()
    while mixer.music.get_busy() == True:
        continue
    PlayedMp3File.close()
    mixer.quit()
    
    if os.path.exists('speech.mp3'):
        os.remove('speech.mp3')
Esempio n. 24
0
 def quit(self):
     try:
         mixer.quit()
         self.state.update("paused", False)
         self.logger.log.info("Quit mixer.")
     except Exception:
         self.logger.log.exception("Failed to quit mixer.")
Esempio n. 25
0
def select_speaker_output():
    if not check_cfg_exists():
        cfg_create()
    print("--- SPEAKER OUTPUT ---")
    mixer.init()
    speakerDevices = [
        get_audio_device_name(x, 0).decode()
        for x in range(get_num_audio_devices(0))
    ]
    mixer.quit()
    # print(speakerDevices)
    for i in speakerDevices:
        if ("AUX" or "Stereo Mix") in i:
            print("\nUsing " + i)
            valid = input("Is this correct (y/n)?  ")
            if valid.lower() == "y":
                return speakerDevices[speakerDevices.index(i)]
    print("\nCould not find VB Audio AUX")

    loop_count = 0
    print("\nAudio Options: ")
    for i in speakerDevices:
        print(str(loop_count) + ".", i)
        loop_count += 1
    print("\nIf VB Audio is not found here, please check it is not disabled.")
    speaker_choice = input("\nPlease select the VB Audio speaker input: ")
    cfg_write("speaker_output", speakerDevices[int(speaker_choice)])
    return speakerDevices[int(speaker_choice)]

    return None
Esempio n. 26
0
def cmd(command):  #function for playing user's commands

    if "what up" in command:
        mixer.init()
        mixer.music.load(
            "C:/Users/wolfp/Desktop/Sasha/modified/sounds/Bidding.mp3")
        mixer.music.play()
        while mixer.music.get_busy():
            pygame.time.Clock().tick(10)

    elif "defeated by victory" in command:
        mixer.init(frequency=30000)
        mixer.music.load(
            "C:/Users/wolfp/Desktop/Sasha/modified/sounds/defeated_by_victory.ogg"
        )
        mixer.music.play()
        while mixer.music.get_busy():
            pygame.time.Clock().tick(10)

    elif "shakespeare" in command:
        mixer.init(frequency=30000)
        mixer.music.load(
            "C:/Users/wolfp/Desktop/Sasha/modified/sounds/shakespeare (1).ogg")
        mixer.music.play()
        while mixer.music.get_busy():
            pygame.time.Clock().tick(13)

    elif "you're weird" in command:
        mixer.init()
        mixer.music.load(
            "C:/Users/wolfp/Desktop/Sasha/modified/sounds/eatmyshorts.wav")
        mixer.music.play()
        while mixer.music.get_busy():
            pygame.time.Clock().tick(1)

    elif "email" in command:
        talk(" who is recieving this")
        toAddr = listenForCmd()
        #if "grandma" in toAddr:
        #recipient.append(contacts[toAddr])
        talk("subject please")
        subject = listenForCmd()
        talk("what is the message")
        msg = listenForCmd()
        email(contacts, subject, msg)

    elif 'listen here' in command:
        mixer.init(frequency=30000)
        mixer.music.load(
            "C:/Users/wolfp/Desktop/Sasha/modified/sounds/listening.mp3")
        mixer.music.play()
        while mixer.music.get_busy():
            pygame.time.Clock().tick(1)

        #mixer.quit()

    elif "stop" in command:
        quit()
    mixer.quit()
Esempio n. 27
0
 def get_devices():
     mixer.init()
     r = [
         get_audio_device_name(x, 0).decode()
         for x in range(get_num_audio_devices(0))
     ]
     mixer.quit()
     return r
Esempio n. 28
0
def at_exit():
    if WIN and LAST is not None:
        mixer.quit()
        for rem_file in LAST:
            try:
                os.remove(rem_file)
            except:
                continue  # if remove fails move on to next`
Esempio n. 29
0
def audio_play():
    mixer.init()
    mixer.music.load('./data/tts_audio/sample.wav')
    print("Starting the Audio Cue")
    mixer.music.play()
    while mixer.music.get_busy():
        time.sleep(0.1)    
    mixer.quit()
    def test_set_num_channels(self):
        mixer.init()

        for i in xrange_(1, mixer.get_num_channels() + 1):
            mixer.set_num_channels(i)
            self.assert_(mixer.get_num_channels() == i)

        mixer.quit()
Esempio n. 31
0
def stop_playback():
    print('One Lap To Green, Stopping Music')
    mixer.music.fadeout(5000)  # Five second long fadeout, then music stops
    time.sleep(
        6
    )  # This keeps the function from being repeatedly called during the fadeout
    mixer.quit(
    )  # Unloads the mixer, required to re-initialize with new sample rates
Esempio n. 32
0
    def test_get_num_channels__defaults_eight_after_init(self):
        mixer.init()
        
        num_channels = mixer.get_num_channels()

        self.assert_(num_channels == 8)

        mixer.quit()
Esempio n. 33
0
    def test_set_num_channels(self):
        mixer.init()

        for i in xrange_(1, mixer.get_num_channels() + 1):
            mixer.set_num_channels(i)
            self.assert_(mixer.get_num_channels() == i)

        mixer.quit()
    def test_get_num_channels__defaults_eight_after_init(self):
        mixer.init()

        num_channels = mixer.get_num_channels()

        self.assert_(num_channels == 8)

        mixer.quit()
Esempio n. 35
0
    def test_quit(self):
        """ get_num_channels() Should throw pygame.error if uninitialized
        after mixer.quit() """

        mixer.init()
        mixer.quit()

        self.assertRaises(pygame.error, mixer.get_num_channels)
 def handleClose(self, *args):
     try:
         self.game.tk.destroy()
     except TclError as e:
         print(e)
     if pygameInstalled:
         mixer.quit()
     sys.exit(0)
Esempio n. 37
0
    def main(self, opts):
        if not opts.sound:
            mixer.quit()
        cpu_timer = 0
        mem_timer = 0
        pid = getpid()
        pu = Process(pid)

        # import after init, to load images
        #   pygame.error: cannot convert without pygame.display initialized
        from sprite.common import Txt
        if opts.viewer:
            from scene.viewer import AnimationViewerScene
            scene = AnimationViewerScene(self.screen)
            display.set_caption('Barbarian - Animation viewer')
        else:
            from scene.battle import BattleScene
            scene = BattleScene(self.screen)
            display.set_caption('Barbarian')
        clock = time.Clock()

        cpu = Txt(FONT, 8, 'CPU: ', RED, 0, 566)
        # 'Resident Set Size', this is the non-swapped
        #   physical memory a process has used.
        mem_rss = Txt(FONT, 8, 'Mem RSS: ', RED, 0, cpu.rect.bottom)
        # 'Virtual Memory Size', this is the total amount of
        #   virtual memory used by the process.
        mem_vms = Txt(FONT, 8, 'Mem VMS: ', RED, 0, mem_rss.rect.bottom)
        fps = Txt(FONT, 8, 'FPS: ', RED, 0, mem_vms.rect.bottom)
        if opts.debug:
            scene.add(cpu, mem_rss, mem_vms, fps)

        while True:
            for evt in event.get():
                scene.process_event(evt)

            # Update all the sprites
            current_time = time.get_ticks()
            if opts.debug:
                fps.msg = 'FPS: {0:.0f}'.format(clock.get_fps())

                if current_time - cpu_timer > opts.cpu_time:
                    cpu_timer = current_time
                    cpu.msg = 'CPU: {0:.1f}%'.format(pu.cpu_percent())

                if current_time - mem_timer > opts.mem_time:
                    mem_timer = current_time
                    mem = pu.memory_info()
                    resident = 'Mem RSS: {0:>7,.0f} Kb'.format(mem.rss / 1024)
                    mem_rss.msg = resident.replace(',', ' ')
                    virtual = 'Mem VMS: {0:>7,.0f} Kb'.format(mem.vms / 1024)
                    mem_vms.msg = virtual.replace(',', ' ')
            scene.update(current_time)

            # Draw the scene
            dirty = scene.draw(self.screen)
            display.update(dirty)
            clock.tick(60)
Esempio n. 38
0
def main():

    openCodeRadio()

    # Initialize sound mixer
    mixer.init()

    # Variables with sources of sound files
    chdir(path.dirname(path.realpath(__file__)))
    rest_tone = path.join("sounds", "rest.mp3")
    work_tone = path.join("sounds", "work.mp3")

    # Program execution variables for later use
    stop = False
    iterations = 1
    work_time, rest_time = 25 * 60, 5 * 60
    init_time = time()
    current_time = time()

    try:
        # Try to eternally loop through work and rest sound files
        while not stop:
            # Work phase
            playSound(work_tone)
            current_time = time() - init_time

            while (current_time < work_time):
                current_time = time() - init_time
                minutes = current_time // 60
                seconds = int(current_time - minutes * 60)

                message = "Work timer {}: {:02n}:{:02n}".format(
                    iterations, minutes, seconds)
                print(message.strip(), end='\r')
                sleep(1)
            init_time = time()

            # Rest phase
            playSound(rest_tone)
            current_time = time() - init_time

            while (current_time < rest_time):
                current_time = time() - init_time
                minutes = current_time // 60
                seconds = int(current_time - minutes * 60)

                message = "Rest timer {}: {:02n}:{:02n}".format(
                    iterations, minutes, seconds)
                print(message.strip(), end='\r')
                sleep(1)

            iterations += 1
            init_time = time()

    except KeyboardInterrupt:
        print("\nGoodbye! Hope you were productive!!")
        mixer.quit()
        exit(0)
Esempio n. 39
0
 def speak_pygame(self):
     mixer.init()
     mixer.pause()
     mixer.music.load(self.speak_result)
     mixer.music.play()
     self.hibernate()
     mixer.music.stop()
     mixer.unpause()
     mixer.quit()
Esempio n. 40
0
def play_sound(sound_file):

    mix.init()
    mix.music.load(sound_file)
    mix.music.play()
    while mix.music.get_busy():
        continue
    mix.quit()
    logging.debug('Playing sound: %s', sound_file)
Esempio n. 41
0
    def test_quit(self):
        """ get_num_channels() Should throw pygame.error if uninitialized
        after mixer.quit() """

        mixer.init()
        mixer.quit()

        self.assertRaises (
            pygame.error, mixer.get_num_channels,
        )
Esempio n. 42
0
 def test_get_raw(self):
     mixer.init()
     try:
         samples = b'abcdefgh' # keep byte size a multiple of 4
         snd = mixer.Sound(buffer=samples)
         raw = snd.get_raw()
         self.assertTrue(isinstance(raw, bytes_))
         self.assertEqual(raw, samples)
     finally:
         mixer.quit()
Esempio n. 43
0
def close_sound(experiment):

    """
	Closes the mixer after the experiment is finished.

	Arguments:
	experiment -- An instance of libopensesame.experiment.experiment
	"""

    mixer.quit()
Esempio n. 44
0
 def todo_test_init__zero_values(self):
     # Ensure that argument values of 0 are replaced with
     # preset values. No way to check buffer size though.
     mixer.pre_init(44100, 8, 1)  # None default values
     mixer.init(0, 0, 0)
     try:
         self.failUnlessEqual(mixer.get_init(), (44100, 8, 1))
     finally:
         mixer.quit()
         mixer.pre_init(0, 0, 0, 0)
Esempio n. 45
0
def finalize():
   print 1
   PDI.quit()
   print 2
   PX.quit()
   print 3
   PG.quit()
   print 4
   SYS.exit()
   print 5
Esempio n. 46
0
 def Load(self, filename):
     with audioread.audio_open(filename) as f:
         self.duration = int(f.duration * 1000)
         self.samplerate = f.samplerate
         self.channels = f.channels
     mixer.quit()
     mixer.init(frequency=self.samplerate, channels=self.channels)
     music.load(filename)
     self.pos = 0
     self.has_music = True
Esempio n. 47
0
def init_sound():
    """ Initialise sound system. """
    if not numpy:
        logging.warning('NumPy module not found. Failed to initialise audio.')
        return False
    if not mixer:
        return False    
    # initialise mixer as silent
    # this takes 0.7s but is necessary to be able to set channels to mono
    mixer.quit()    
    return True
Esempio n. 48
0
def handler(signal, frame):
    try:
        # Close and quit everything on CTRL+C
        midi.close()
        pymidi.quit()
        pymix.quit()
        pygame.quit()
    except Exception:
        pass

    sys.exit(0)
Esempio n. 49
0
 def NEWBUF_test_newbuf(self):
     mixer.init(22050, -16, 1)
     try:
         self.NEWBUF_export_check()
     finally:
         mixer.quit()
     mixer.init(22050, -16, 2)
     try:
         self.NEWBUF_export_check()
     finally:
         mixer.quit()
Esempio n. 50
0
 def test_load_buffer_bytearray(self):
     """Test loading from various buffer objects."""
     mixer.init()
     try:
         samples = b'\x00\xff' * 24
         snd = mixer.Sound(bytearray(samples))
         raw = snd.get_raw()
         self.assertTrue(isinstance(raw, bytes_))
         self.assertEqual(raw, samples)
     finally:
         mixer.quit()
Esempio n. 51
0
 def test_sound_mixer(self):
     """Tests that the app can initialize the pygame audio mixer."""
     import pygame.mixer as mix
     mix.init()
     # check that the mixer initialized
     self.assertIsNotNone(mix.get_init())
     # try to play a sound
     mix.music.load(settings.ARMED_SOUND_FILE)
     mix.music.play()
     while mix.music.get_busy():
         continue
     mix.quit()
Esempio n. 52
0
def consumer_thread():
    """ Audio signal queue consumer thread. """
    # initialise mixer as silent
    # this is necessary to be able to set channels to mono
    mixer.quit()
    while drain_message_queue():
        empty = drain_tone_queue()
        # generate and play chunks
        play_sound()
        # do not hog cpu
        if empty and next_tone == [None, None, None, None]:
            pygame.time.wait(tick_ms)
Esempio n. 53
0
 def _check_quit(self):
     """Quit the mixer if not running a program and sound quiet for a while."""
     if self.next_tone != [None, None, None, None]:
         self.quiet_ticks = 0
     else:
         self.quiet_ticks += 1
         if not self._persist and self.quiet_ticks > self.quiet_quit:
             # mixer is quiet and we're not running a program.
             # quit to reduce pulseaudio cpu load
             # this takes quite a while and leads to missed frames...
             if mixer.get_init() is not None:
                 mixer.quit()
             self.quiet_ticks = 0
Esempio n. 54
0
def check_quit():
    """ Quit the mixer if not running a program and sound quiet for a while. """
    global quiet_ticks
    if next_tone != [None, None, None, None]:
        quiet_ticks = 0
    else:
        quiet_ticks += 1
        if not persist and quiet_ticks > quiet_quit:
            # mixer is quiet and we're not running a program.
            # quit to reduce pulseaudio cpu load
            # this takes quite a while and leads to missed frames...
            if mixer.get_init() is not None:
                mixer.quit()
            quiet_ticks = 0
Esempio n. 55
0
 def test_array_interface(self):
     mixer.init(22050, -16, 1)
     try:
         snd = mixer.Sound(as_bytes('\x00\x7f') * 20)
         d = snd.__array_interface__
         self.assertTrue(isinstance(d, dict))
         if pygame.get_sdl_byteorder() == pygame.LIL_ENDIAN:
             typestr = '<i2'
         else:
             typestr = '>i2'
         self.assertEqual(d['typestr'], typestr)
         self.assertEqual(d['shape'], (20,))
         self.assertEqual(d['strides'], (2,))
         self.assertEqual(d['data'], (snd._samples_address, False))
     finally:
         mixer.quit()
Esempio n. 56
0
 def test_load_buffer_array(self):
     """Test loading from various buffer objects."""
     mixer.init()
     try:
         import array
         samples = b'\x00\xff' * 24
         arsample = array.array('b')
         if hasattr(arsample, 'frombytes'):
             # Python 3
             arsample.frombytes(samples)
         else:
             arsample.fromstring(samples)
         snd = mixer.Sound(bytearray(samples))
         raw = snd.get_raw()
         self.assertTrue(isinstance(raw, bytes_))
         self.assertEqual(raw, samples)
     finally:
         mixer.quit()
Esempio n. 57
0
    def test_get_raw(self):
        from ctypes import pythonapi, c_void_p, py_object

        try:
            Bytes_FromString = pythonapi.PyBytes_FromString
        except:
            Bytes_FromString = pythonapi.PyString_FromString
        Bytes_FromString.restype = c_void_p
        Bytes_FromString.argtypes = [py_object]
        mixer.init()
        try:
            samples = as_bytes('abcdefgh') # keep byte size a multiple of 4
            snd = mixer.Sound(buffer=samples)
            raw = snd.get_raw()
            self.assertTrue(isinstance(raw, bytes_))
            self.assertNotEqual(snd._samples_address, Bytes_FromString(samples))
            self.assertEqual(raw, samples)
        finally:
            mixer.quit()
Esempio n. 58
0
def doSomething():
    mixer.quit()
    try:
        os.remove("temp.mp3")
    except:
        pass
    try:
        os.remove("temp2.mp3")
    except:
        pass

    v = textPad.index(INSERT)
    if v != '1.0':
        t4 = Toplevel(root)
        t4.title("Save")
        t4.iconbitmap('help.ico')
        t4.geometry('290x140+200+250')
        t4.configure(background='#ffffff')
        t4.transient(root)

        def nt():
            t4.destroy()

        def sve():
            save()
            t4.destroy()
            qt()

        def qt():
            quit_()

        Label(t4, text="     ", image=helpimage).place(x=20, y=20)
        Label(t4, text="Do you want save this file ?", bg='#ffffff', font=hel).place(x=70, y=25)
        frm = Frame(t4, bg='#efefef', height='40')
        frm.pack(side=BOTTOM, anchor='sw', fill=X)
        Button(frm, text="Save", relief='groove', command=sve).place(x=10, y=5, width=80)
        Button(frm, text="Don't Save", relief='groove', command=qt).place(x=105, y=5, width=80)
        Button(frm, text="Cancel", relief='groove', command=nt).place(x=200, y=5, width=80)
    else:
        root.destroy()
Esempio n. 59
0
    def __init__(self):
        rospy.init_node('sound_play')
        self.diagnostic_pub = rospy.Publisher("/diagnostics", DiagnosticArray)

        rootdir = os.path.join(os.path.dirname(__file__),'..','sounds')
        
        self.builtinsoundparams = {
                SoundRequest.BACKINGUP              : (os.path.join(rootdir, 'BACKINGUP.ogg'), 0.1),
                SoundRequest.NEEDS_UNPLUGGING       : (os.path.join(rootdir, 'NEEDS_UNPLUGGING.ogg'), 1),
                SoundRequest.NEEDS_PLUGGING         : (os.path.join(rootdir, 'NEEDS_PLUGGING.ogg'), 1),
                SoundRequest.NEEDS_UNPLUGGING_BADLY : (os.path.join(rootdir, 'NEEDS_UNPLUGGING_BADLY.ogg'), 1),
                SoundRequest.NEEDS_PLUGGING_BADLY   : (os.path.join(rootdir, 'NEEDS_PLUGGING_BADLY.ogg'), 1),
                }
        
        self.mutex = threading.Lock()
        sub = rospy.Subscriber("robotsound", SoundRequest, self.callback)
        self.mutex.acquire()
        self.no_error = True
        self.initialized = False
        self.active_sounds = 0
        self.sleep(0.5) # For ros startup race condition
        self.diagnostics(1)
        while not rospy.is_shutdown():
            while not rospy.is_shutdown() and self.mixer_init():
                self.no_error = True
                self.initialized = True
                self.mutex.release()
                try:
                    self.idle_loop()
                    # Returns after inactive period to test device availability
                    #print "Exiting idle"
                except:
                    rospy.loginfo('Exception in idle_loop: %s'%sys.exc_info()[0])
                finally:
                    self.mutex.acquire()
                    mixer.quit()
            self.diagnostics(2)
        self.mutex.release()
Esempio n. 60
0
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')