예제 #1
0
 def start(self):
     '''
     Central method that dislpays the main menu
     '''
     if self.sound:
         mixer.stop()
         menu_music.play(-1)
     self.main_menu.mainloop(self.win, bgfun=self.draw_bg)  # Show the menu
예제 #2
0
def stop_sound():
    """
    Stops all sound channels. Equivalent to `pygame.mixer.stop()`.
    """
    try:
        mixer.stop()
    except pygame.error:
        pass
예제 #3
0
def voice_assistant():
    while True:
        # Record Audio
        r = sr.Recognizer()
        with sr.Microphone() as source:
            print("Please wait. Calibrating microphone...")
            # listen for 5 seconds and create the ambient noise energy level
            r.adjust_for_ambient_noise(source, duration=1)
            print("Say something!")
            audio = r.listen(source)

        # Speech recognition using Google Speech Recognition
        data = ""
        try:
            # Uses the default API key
            # To use another API key: `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
            data = r.recognize_google(audio, language="fr-FR")
            print("Vous avez dis: " + data)
        except sr.UnknownValueError:
            print("Google Speech Recognition could not understand audio")
        except sr.RequestError as e:
            print(
                "Could not request results from Google Speech Recognition service; {0}"
                .format(e))

        if "blague" in data:
            blague()
        if "actualité" in data:
            get_news()
        if "comment tu vas" in data:
            speak("Je vais bien merci")

        if "heure" in data:
            heure = time.strftime("%H")
            minute = time.strftime("%M")
            speak("Il est {} heure {}".format(heure, minute))
        if "quel temps fait-il à" in data or "météo" in data:
            data = data.split(" ")
            print(data)
            location = data[len(data) - 1]
            temp = get_weather(location)
            speak("il fait {} degré à {}".format(temp, location))
        if "musique" in data:
            random_song = os.listdir('music/song')
            print(random_song)
            i = randint(0, len(random_song) - 1)
            show_title.configure(text=random_song[i])
            song = "music/song/" + random_song[i]
            mixer.stop()
            print("je joue {}".format(song))
            Image = PhotoImage(file=icon_lookup["play"])
            play_button.create_image(24, 24, image=Image)
            mixer.music.load(song)
            mixer.music.play()
        if "pause" in data:
            mixer.music.pause()
            Image = PhotoImage(file=icon_lookup["pause"])
            play_button.create_image(24, 24, image=Image)
예제 #4
0
 def player_stop(self) -> None:
     pmixer.stop()
     self.player_status = PlayerStatus.STOPPED
     self.ui.btn_pause_play.setIcon(
         QtGui.QIcon(
             str(Path(BASE_PATH, self.cfg.svg_path,
                      self.cfg.svg_btn_play))))
     self.ui.btn_pause_play.clicked.disconnect()
     self.ui.btn_pause_play.clicked.connect(self.player_play)
예제 #5
0
    def __init__(self):
        State.State.__init__(self)
        PX.stop()
        """self.sound = PX.Sound("music/march.wav")
        self.sound.play()"""
        Intro.FONT = PF.Font("fonts/red_october.ttf", 18)
        img_1 = PI.load("sprites/images/intro1.jpg").convert()
        img_2 = PI.load("sprites/images/intro2.jpg").convert()
        img_3 = PI.load("sprites/images/intro3.jpg").convert()
        img_4 = PI.load("sprites/images/intro4.jpg").convert()
        img_5 = PI.load("sprites/images/instructions.jpg").convert()
        self.strings1 = []
        self.strings2 = []
        self.images = []
        self.index = -1
        self.time = 0

        self.strings1.append("In a secret government lab, deep " +
                             "within a deserted Russian town,")
        self.strings2.append("Scientists concocted experiments on" +
                             " a large group of specimens.")

        self.strings1.append("Through a series of radioactive experiments" +
                             " and countless injections")
        self.strings2.append("a powerful new age weapon was created.")

        self.strings1.append("A fierce creature: the product of science" +
                             " and one's worst fears")
        self.strings2.append("was brought into this world as a dangerous " +
                             "and sentient being.")

        self.strings1.append("It is now time for you to make your escape " +
                             "from the lab,")
        self.strings2.append("for you are now, the Gamma Ray Kitten.")
        self.strings1.append("")
        self.strings2.append("")

        self.images.append(img_1)
        self.images.append(img_2)
        self.images.append(img_3)
        self.images.append(img_4)
        self.images.append(img_5)

        self.surf1 = Intro.FONT.render(self.strings1[self.index], True,
                                       (255, 0, 0))
        self.surf2 = Intro.FONT.render(self.strings2[self.index], True,
                                       (255, 0, 0))
        self.xy1 = ((400 - self.surf1.get_width() / 2,
                     500 - self.surf1.get_height()))
        self.xy2 = ((400 - self.surf2.get_width() / 2,
                     500 + self.surf2.get_height()))

        self.fadein = 0
        self.fadeout = 255
        self.fade_value = 100
예제 #6
0
 def setVisible(self, visible):
     # Response to toggle between overlays
     if visible:
         self.startTime = time.time()
         mixer.music.load(self.musicPath)
         mixer.music.play()
         mixer.music.set_volume(.2)
         self.overlay.show()
     else:
         self.startTime = time.time()
         mixer.stop()
         self.overlay.hide()
예제 #7
0
 def __init__(self, score):
     State.__init__(self)
     self.color = PC.Color("black")
     self.time = 0.0
    
     PX.stop() 
     Globals.ISMAINMENU = True
     
     Globals.WORLD.clear()
     Globals.SCREEN.fill(PC.Color("black"))
     self.score = score
     Globals.ISLEVELONE = False
예제 #8
0
def speak(text):
    global i
    tts = gTTS(text=text, lang='en', slow=False)
    tts.save('speech{}.mp3'.format(i % 2))
    # playback the speech
    mixer.music.load('speech{}.mp3'.format(i % 2))
    mixer.music.play()
    # wait for playback to end
    while mixer.music.get_busy():
        time.sleep(.1)
    mixer.stop()
    i += 1
예제 #9
0
def pauseMusic(hi):
    global playPause
    draw.delete(playPause)
    playPause = draw.create_image(screen_width / 2,
                                  screen_height / 2 + 50,
                                  image=playTk)
    draw.tag_bind(playPause, '<ButtonPress-1>', playMusic)
    try:
        mixer.music.pause()
    except:
        print("Couldn't pause music?")
        mixer.stop()
        pass
예제 #10
0
파일: STT.py 프로젝트: SKY-ALIN/foodbot
 def pip(self):
     """
     Подача звукогого сигнала.
     """
     mixer.init()
     f = open("pip.mp3", "rb")
     mixer.music.load(f)
     mixer.music.play()
     while mixer.music.get_busy():
         time.sleep(0.1)
     mixer.stop()
     mixer.quit()
     f.close()
예제 #11
0
 def soundSRV(self, req):
     if(req.path2file!=""):
         self.sound_file = req.path2file
         try:
             mixer.stop()
             self.sound = mixer.Sound(self.sound_file)
             self.sound.set_volume(1.0)
             self.sound.play(-1)
         except:
             pass
     else:
         mixer.stop()
     return ()
예제 #12
0
    def stop(self):
        """<DOC>
		Stops the currently playing sound (if any).
		
		Example:
		>>> from openexp.sampler import sampler
		>>> src = exp.get_file('my_sound.ogg')
		>>> my_sampler = sampler(exp, src)
		>>> my_sampler.play()
		>>> self.sleep(100)
		>>> my_sampler.stop()
		</DOC>"""

        mixer.stop()
예제 #13
0
    def stop(self):

        """<DOC>
		Stops the currently playing sound (if any).

		Example:
		>>> from openexp.sampler import sampler
		>>> src = exp.get_file('my_sound.ogg')
		>>> my_sampler = sampler(exp, src)
		>>> my_sampler.play()
		>>> self.sleep(100)
		>>> my_sampler.stop()
		</DOC>"""

        mixer.stop()
예제 #14
0
    def click_skip(self):
        dir_path = os.path.dirname(os.path.realpath(__file__))
        #dir of the folder with songs
        dirs = "change dir here"
        #randomly chose from the dir any song
        songs_get = os.listdir(dirs)

        randoms = random.choice(songs_get)
        dirr = (dir_path + "/" + dirs + randoms)

        mixer.stop()
        mixer.music.load(dirr)
        mixer.music.play()
        self.label.setText(randoms)
        self.update()
예제 #15
0
 def say(self, what, l='ru'):
 	mixer.init()
 	print(datetime.datetime.today().strftime("%H:%M:%S -"), what)
 	tts=gTTS(text=what, lang=l)
 	mp3 = "speech.mp3"
 	tts.save(mp3)
 	f=open(mp3,"rb")
 	mixer.music.load(f)
 	mixer.music.play()
 	while mixer.music.get_busy():
 		time.sleep(0.1)
 	mixer.stop()
 	mixer.quit()
 	f.close()
 	os.remove(mp3)
예제 #16
0
def practice():
    mixer.stop()

    game = Game(team1, no_team, sound=False)  # initialize the game
    """ Game loop """
    while not game.end:  # Game loop
        clock.tick(args.fps)  # FPS

        game.check_interruptions()  # Check for special keys (quit, pause, etc)

        game.draw(win, hints=False)
        game.practice_instr_draw(win)
        game.next()

        pygame.display.update()  # refresh screen

    global game_menu
    game_menu.start()  # Return to main menu
예제 #17
0
파일: thread.py 프로젝트: amitj4056/sudo
def print_timeThread2(threadName, delay):
    # Pass the path to your zuliprc file here.
    client = zulip.Client(config_file="./zuliprc")
    # Get the 3 last messages sent by "*****@*****.**" to the stream "Verona"
    request = {
        'use_first_unread_anchor':
        True,
        'num_before':
        1,
        'num_after':
        0,
        'narrow': [{
            'operator': 'sender',
            'operand': '*****@*****.**'
        }, {
            'operator': 'is',
            'operand': 'private'
        }],
        'client_gravatar':
        True,
        'apply_markdown':
        True
    }  # type: Dict[str, Any]
    result = client.get_messages(request)
    print(result)

    mixer.init()
    # Get the text and convert to mp3 file
    tts = gTTS(text="saurabh is good boy", lang='en', slow=False)
    tts.save('speech{}.mp3'.format(0))
    # playback the speech
    mixer.music.load('speech{}.mp3'.format(0))
    mixer.music.play()
    # wait for playback to end
    while mixer.music.get_busy():
        time.sleep(.1)
    mixer.stop()

    # try to remove the temp files. You'll likely be left with 1 to clean up
    try:
        os.remove('speech0.mp3')
    except:
        pass
예제 #18
0
def practice():
    '''
    Play the game with only one team for practice
    '''

    mixer.stop()
    game = Game(team1, no_team, sound=False)  # initialize the game

    while not game.end:  # Game loop
        clock.tick(args.fps)  # FPS

        game.draw(win, hints=False)
        game.practice_instr_draw(win)
        game.next()

        pygame.display.update()  # refresh screen

    global game_menu
    game_menu.start()  # Return to main menu
예제 #19
0
    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)
예제 #20
0
def play(win, team1, team2, sound, difficulty, cam):
    '''
    Play the game: This is the central function that runs the game
    '''

    mixer.stop()
    game = Game(team1, team2, sound, difficulty, cam)  # initialize the game

    while not game.end:  # Game loop
        clock.tick(args.fps)  # FPS

        game.draw(win)
        if game.pause:
            game.pause_draw(win)  # Draws on-top of the (frozen) game
        game.next()

        pygame.display.update()  # refresh screen

    global game_menu
    if not args.menu_off:
        game_menu.start()  # Return to main menu
예제 #21
0
def play(win, team1, team2, sound, difficulty, cam):  # Play the entire game
    mixer.stop()
    game = Game(team1, team2, sound, difficulty, cam)  # initialize the game
    """ Game loop """
    while not game.end:  # Game loop
        clock.tick(args.fps)  # FPS

        game.check_interruptions()  # Check for special keys (quit, pause, etc)

        if game.pause:  # game is paused - display pause menu
            game.draw(win)
            game.pause_draw(win)  # Draws on-top of the (frozen) game
        else:  # Continue with the game
            game.draw(win)
            game.next()

        pygame.display.update()  # refresh screen

    global game_menu
    if not args.menu_off:
        game_menu.start()  # Return to main menu
예제 #22
0
    def check_interruptions(self):
        """
        Check for special keyboard buttons

        Sets internal flags to pause, quit the game or run it in debug mode
        """
        for event in pygame.event.get():
            if event.type == pygame.QUIT:  # Quit
                mixer.pause()
                if self.sound:
                    three_whistles.play()
                self.end = True
                pygame.quit()

            if event.type == pygame.KEYDOWN:

                if event.key == pygame.K_ESCAPE:  # Pause menu
                    self.pause = not self.pause
                    if self.pause:
                        mixer.pause()
                        if self.sound:
                            single_long_whistle.play()
                    else:
                        if self.sound:
                            single_short_whistle.play()
                            applause.play(-1)

                if event.key == pygame.K_BACKSPACE:  # Return to main menu
                    mixer.stop()
                    self.end = True

                if event.key == pygame.K_SPACE:  # Toggle whether to maintain formation
                    self.team1.maintain_formation = not self.team1.maintain_formation

                if event.key == pygame.K_d:  # Debug mode
                    mods = pygame.key.get_mods()
                    if mods & pygame.KMOD_CTRL and mods & pygame.KMOD_SHIFT and mods & pygame.KMOD_ALT:
                        self.debug = not self.debug
예제 #23
0
def mainScript():
    currentDate2 = datetime.now()
    currentDate = currentDate2.strftime("%Y%m%d")

    #starting the mixer for playing the audio files
    mixer.init()

    #opening the calendar file, "calendar.txt" should be the name of the file containing the events
    with open("/path/to/calendar.txt", "r") as doc:

        #creating the arrays for the start and end time of the events
        startTime = []
        endTime = []

        #getting the start time and end time from the document
        for ln in doc:
            if ln.startswith(currentDate):
                #the number 30 is the removed character, removing all of the excess numbers which aren't needed
                startTime.append(ln)

    print(len(startTime))
    #print(startTime[0])

    #the amount of times the loop is going to repeat
    repeatVar = len(startTime)

    #the big loop
    while repeatVar > 0:

        #slicing string up
        def printYear(sliceYear):
            return sliceYear[:4]

        def printMonth(sliceMonth):
            return sliceMonth[4:6]

        def printDay(sliceDay):
            return sliceDay[6:8]

        def printTime(sliceTime):
            return sliceTime[9:13]

        def minSlice(sliceMin):
            return sliceMin[2:4]

        def hourSlice(sliceHour):
            return sliceHour[0:2]

        #Current date and time
        dateNow = datetime.now()
        currentMinute = dateNow.strftime("%M")
        currentHour = dateNow.strftime("%H")

        #Prints the results of the date
        print("The start of the event is: " + printMonth(startTime[0]) + "/" +
              printDay(startTime[0]) + "/" + printYear(startTime[0]) + " at " +
              printTime(startTime[0]))

        #getting the start time of the event
        eventStartTime = printTime(startTime[0])

        #eventStartTime = str(eventStartTime)
        #eventStartTime.lstrip('0')

        #converting strings to integers
        currentHour = int(currentHour)
        currentMinute = int(currentMinute)

        #slicing up the variable
        minutePlace = minSlice(eventStartTime)

        #turning this variable into an integer for the if statement
        minutePlace = int(minutePlace)

        #removing characters
        hourPlace = hourSlice(eventStartTime)

        hourPlace = int(hourPlace)

        #removing 10 minutes from the event start time
        if minutePlace >= 21:
            minutePlace = minutePlace - 21
        else:
            minutePlace = minutePlace + 39
            hourPlace = hourPlace - 1

        minutePlace = str(minutePlace)

        if len(minutePlace) == 1:
            minutePlace = "0" + minutePlace

        #turning the variable back into a string so that the characters will merge together, and not add
        minutePlace = str(minutePlace)

        hourPlace = str(hourPlace)

        #adding the variables
        timeComparingVar = hourPlace + minutePlace

        #turning the comparing variable into an integer so that it can be properly compared
        timeComparingVar = int(timeComparingVar)

        #getting the current time in an integer format
        currentMinuteHour = int((currentHour * 100) + currentMinute)

        #converting and printing the combination of hours and minutes
        currentMinuteHour = int(currentMinuteHour)

        eventStartTime = int(eventStartTime)

        checkEqual = (currentMinuteHour == eventStartTime)
        while checkEqual != True:

            print(currentMinuteHour)
            print(timeComparingVar)

            #getting the updated time of the computer
            dateNow = datetime.now()
            currentMinute = dateNow.strftime("%M")
            currentHour = dateNow.strftime("%H")

            #redoing the comparison variables
            currentMinuteHour = (dateNow.strftime("%H") + currentMinute)
            currentMinuteHour = int(currentMinuteHour)

            #checking if the times are the same
            checkEqual = (currentMinuteHour == timeComparingVar)

            #waiting 15 seconds, can be changed as necessary
            time.sleep(15)

        #can be changed to the sound when needed, but this is what will happen when the start time and scheduled time are the same
        print("yay ;D")
        mixer.init()
        mixer.stop()
        mixer.music.load(ten_minute_alerts[random.randint(
            0,
            len(ten_minute_alerts) - 1)])
        mixer.music.play()
        print(datetime.now())

        time.sleep(600)

        print("yay ;D")
        mixer.init()
        mixer.stop
        mixer.music.load(five_minute_alerts[random.randint(
            0,
            len(five_minute_alerts) - 1)])
        mixer.music.play()
        print(datetime.now())

        #deleting the variable off of the array
        del startTime[0]

        repeatVar = len(startTime)
예제 #24
0
def stop_sound():
    try:
        mixer.stop()
    except pygame.error:
        pass
예제 #25
0
 def stopMusic(self):
     mixer.stop()
예제 #26
0
def shutdown():
    mixer.stop()
    app.destroy()
예제 #27
0
 def _stop(self):
     pm.stop()
예제 #28
0
 def _stop(self):
     mixer.stop()
예제 #29
0
 def stop(self):
     mixer.stop()
예제 #30
0
 def stopAllSounds(self):
     '''Stops all sounds that are currently playing'''
     mixer.stop()
예제 #31
0
	def stop(self):

		mixer.stop()
예제 #32
0
def start(directory):
    """
    Creates a playlist from a given directory, using only MP3 and WAV files.
    """
    global paused
    global skipped
    global previous
    global now_playing
    global playing
    was_paused = False
    files = []
    for (dirpath, _, filenames) in os.walk(directory):
        for file in filenames:
            files.append(os.path.join(dirpath, file))  #Creates a list of files
    i = 0
    while i < len(files) - 1:
        now = files[i]
        if now.split('.')[-1].lower() not in ['mp3', 'wav']:
            del files[i]  #Removes every file that isn't MP3 or WAV
        else:
            i += 1
        print(f'Size: {len(files)}', 'USB', end='')
    i = 0
    fail_count = 0
    while i < len(files):  #Starts playing files while it's not at the end.
        try:
            if fail_count > 5:  #If playing failes 5 times, breaks out (The media was removed probably)
                break
            item = files[i]
            i += 1
            now_playing = os.path.basename(item)
            if now_playing.split('.')[-1].lower(
            ) == 'mp3':  #If it's an MP3 file, sets the requency to the files sample rate
                tmp = mutagen.mp3.MP3(item)
                mixer.init(frequency=tmp.info.sample_rate)
            else:  #If it's a WAV file, sets the requency to the files sample rate
                tmp = wave.open(item)
                mixer.init(frequency=tmp.getframerate())
            del tmp
            print(f'Now playing {now_playing}', 'USB player')
            mixer.music.load(item)
            mixer.music.set_volume(volume)
            mixer.music.play()
            playing = True
            while True:
                if mixer.music.get_volume(
                ) != volume:  #Sets the volume, if it's changed during replay
                    mixer.music.set_volume(volume)
                if not mixer.music.get_busy(
                ) and not paused:  #If the music isn't paused, and the play finished exits the loop
                    break
                if skipped:  #If skipped, stops the music
                    mixer.music.stop()
                    skipped = False
                if paused:  #If paused, pauses the music
                    mixer.music.pause()
                    was_paused = True
                elif was_paused:  #If not paused, but was, un pauses the player
                    mixer.music.unpause()
                    was_paused = False
                if previous:  #Skips back one
                    i -= 2
                    mixer.music.stop()
                    previous = False
                if kill:  #If killed, stops the music
                    mixer.stop()
            playing = False
            now_playing = "none"
            if fail_count != 0:  #If finished, and failcount wasn't 0, resets it (If a file was unplayable)
                fail_count = 0
            if kill:  #If kill, returns
                break
        except Exception as ex:
            print('Exception occured during playback', 'USB player')
            print(f'Exception: {ex}', 'USB player')
            fail_count += 1
예제 #33
0
def play_boom():
    pm.stop()
    boom= pm.Sound("sounds/boom.wav")
    boom.set_volume(0.2)
    boom.play()
예제 #34
0
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()
예제 #35
0
파일: hfmix.py 프로젝트: pjelelhml/Python
def termina():
    mixer.stop()
    app.destroy()
예제 #36
0
import RPi.GPIO as GPIO
from pygame import mixer as pm
import time
import glob
import random
import sys

soundfiles = glob.glob("music_player/*.mp3")


def play_music():
    pm.init()
    pm.music.load(random.choice(soundfiles))
    pm.play()


if __name__ == '__main__':
    try:
        while True:
            play_music()
            time.sleep(5)

        # Reset by pressing CTRL + C
    except KeyboardInterrupt:
        print("Music player stopped by User")
        pm.stop()
        sys.exit()

    finally:
        GPIO.setwarnings(False)
        GPIO.cleanup()
예제 #37
0
 def OnExit(self):
     mixer.stop()
     mixer.quit()
예제 #38
0
def shutdown():
    # if askokcancel(title="Are you sure?", message="Do you really want to quit?"):
    # Stop any paying tracks
    mixer.stop()
    # Close the application
    app.destroy()
예제 #39
0
 def __exit__(self, exc_type, exc_val, exc_tb):
     mixer.stop()
예제 #40
0
def shutdown():
    mixer.stop()
    app.destroy()