Ejemplo n.º 1
0
 def playAdhan(self, prayerTime, prayerName):
     adhan = AudioPlayer("./Adhans/AdhanFajr.mp3") if prayerName == "Fajr" \
         else AudioPlayer("./Adhans/Adhan.mp3")
     print(prayerName, prayerTime)
     adhan.play(block=True)
     time.sleep(10)
     adhan.stop()
     adhan.close()
Ejemplo n.º 2
0
 def __init__(self, TCP, ip, port):
     Client.__init__(self, TCP, ip, port)
     self.audio = AudioPlayer()
     self.audio.createAudioPlayerStream()
     self.setDaemon(True)  #detached thread
     self.lupdate = Lock()
     self.filter = None
Ejemplo n.º 3
0
 def play(self, subdirectory):
     target = self.directory + '/' + subdirectory
     snippet = random.choice(os.listdir(target))
     print(' ' + subdirectory + ': ' + str(snippet))
     AudioPlayer(target + '/' + snippet).play(block=True)
     time.sleep(.05)
     while (self.chance(75)):
         time.sleep(.2)
Ejemplo n.º 4
0
    def set(self, song):
        force_path(song)
        if self.audioplayer:
            self.close()

        self.audioplayer = AudioPlayer(song)
        self.audioplayer.volume = self.audio_volume
        self.current_song = song
Ejemplo n.º 5
0
def play_sound(PATH):
    global ap

    if ap is not None:
        stop_sound()

    ap = AudioPlayer(PATH)
    ap.play(block=False)
Ejemplo n.º 6
0
 def makePlayers(self):
     """ Make instances of audio players required for different tracks. 
     """
     if self.players:
         del self.players
     self.players = list()
     for i in range(self.playerCount):
         self.players.append(AudioPlayer())
         self.players[i].setFile(self.board.filelist[i])
Ejemplo n.º 7
0
def load():
    global player, root
    fname = filedialog.askopenfilename()
    if fname:
        player = AudioPlayer(fname)
        changevolume(0)  # update UI
        namelabel.config(text=os.path.basename(player.fullfilename))
        try:
            player.play()
        except Exception as e:
            messagebox.showerror('Error', e)
Ejemplo n.º 8
0
 def __init__(self, root, **args):
     super().__init__(root, **args)
     print("Initialize Application")
     #Set up applicatiom variables, create widgets, grid widgets onto main frame
     self.root = root
     self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
     self.audioplayer = AudioPlayer()
     self.create_widgets()
     self.grid_widgets()
     self.thread = SiriListenThread(KartSiriControlModule(self))
     self.thread.start()
Ejemplo n.º 9
0
def audio(text: str, title: str) -> AudioPlayer:
    """Convert text to audio."""
    title = f"{title}.mp3" if not title.endswith(".mp3") else title
    audio_path = Path(FILE_PATH / "audio")
    audio_path.mkdir(parents=True,
                     exist_ok=True)  # Create directory if doesn't exists.
    audio_path = Path(audio_path / title).as_posix()
    speech = gTTS(
        text=text, lang="en", slow=False
    )  # Due to slow=False, the converted audio should have a high speed.
    speech.save(audio_path)
    return AudioPlayer(audio_path)
Ejemplo n.º 10
0
def load_song():
    global player
    pick_song = tk.filedialog.askopenfile()
    name = (str(pick_song.name))
    player = AudioPlayer(name)
    extract_name = name.split("/")
    song_track = extract_name[-1]
    song_title = tk.Label(text='                                                                                                                                                                            ')
    song_title.place(x=250, y=20, anchor="center")
    play()
    song_title = tk.Label(text=song_track)
    song_title.place(x=250, y=20, anchor="center")
    play()
Ejemplo n.º 11
0
def play_mp3_with_volume(time_to_play=5):
    """
        Reference: https://pypi.org/project/audioplayer/
    """
    import time
    from audioplayer import AudioPlayer

    player = AudioPlayer(song_file)
    player.volume = 15

    player.play(loop=False, block=False)
    time.sleep(time_to_play)      # default, play in 5s, then stop
    player.stop() 
Ejemplo n.º 12
0
def load_playlist():
    global player , songs , pick_play_list
    pick_play_list=tk.filedialog.askdirectory()
    song_list = os.listdir(pick_play_list)
    for choose in song_list:
        songs.append(choose)
    # need it to make a system where it keeps playing
    pick_song = songs[0]
    player = AudioPlayer(pick_play_list + "/" + pick_song)
    # note the song names do not clear and update
    song_title = tk.Label(text=pick_song)
    song_title.place(x=250, y=20, anchor="center")
    play()
Ejemplo n.º 13
0
    def build(self):
        """Called in application start"""

        self.update_backgrounds()

        # initialize objects
        self.layout = ClockLayout()
        self.layout.ids.drag_area.app = self
        self.audioplayer = AudioPlayer()

        # start ticking
        Clock.schedule_interval(self.tick, 1 / 1.)
        return self.layout
Ejemplo n.º 14
0
    def __init__(self):
        super().__init__()
        self.initUI()
        self.button = QPushButton(self)
        self.button.setText("На паузу")
        # флаг, с помощью которого мы будем узнавать, на паузе ли наше аудио. Изначально False - аудио воспроизводится
        self.is_pause = False
        self.button.clicked.connect(self.pause)
        # аудиоплейер
        self.player = AudioPlayer("file_example_MP3_700KB.mp3")
        # можно установить громкость с помощью self.player.volume(n), где n целое число от 0 до 100

        # запускаем воспроизведение
        self.player.play()
Ejemplo n.º 15
0
def insABSwitch(app):
    if (app.timer % 500 == 0):
        app.isInsAB *= -1
        if app.timer >= 1000:
            speechRecognition(app)
            if len(app.speechRecognized
                   ) >= 9 and app.speechRecognized[0:9] == "hey let's":
                app.isStarted = True
                app.isInsC = True
                app.timer = 0
                ser.write("c".encode('utf-8'))
            else:
                AudioPlayer("errorMessage.mp3").play(block=True)
    return None
Ejemplo n.º 16
0
def gtts_daemon():
    while BOT.is_pooling:
        try:
            response = QUEUE.get(block=False) # This blocks and hangs the program entirely
            file_name = os.path.join(TEMP_DIR, f'gtts_{datetime.now().microsecond}.mp3')
            response.save(file_name)
            sound = AudioPlayer(file_name)
            sound.volume = SETTINGS.get('volume', 100)
            sound.play(block=True)
            os.remove(file_name)
            QUEUE.task_done()
        except queue.Empty:
            pass # Ignore and try again later
        except Exception as err:
            os.remove(file_name)
            LOGGER.error(err, exc_info=True)
        time.sleep(1) # Lessen the CPU impact.
Ejemplo n.º 17
0
def muter():
    while True:
        sessions = AudioUtilities.GetAllSessions()
        for session in sessions:
            volume = session.SimpleAudioVolume
            # if session.Process:
            # print(session.Process.name())
            if session.Process and session.Process.name() == "Spotify.exe":
                # print(spotify.song())
                try:
                    if spotify.song() == "Advertisement":
                        print("Playing interlude song")
                        volume.SetMute(1, None)
                        AudioPlayer("soundtrack.wav").play(block=True)
                    else:
                        volume.SetMute(0, None)
                except:
                    continue
Ejemplo n.º 18
0
def speechRecognition(app):

    with sr.Microphone() as source:
        print("Please wait. Calibrating microphone...")
        # listen for 5 seconds and create the ambient noise energy level

        AudioPlayer("beep.wav").play(block=True)
        app.r.adjust_for_ambient_noise(source, duration=1)
        print("Say something!")
        audio = app.r.listen(source)

        # recognize speech using Sphinx
    try:
        app.speechRecognized = app.r.recognize_sphinx(audio)
        print("Sphinx thinks you said '" + app.speechRecognized + "'")
    except sr.UnknownValueError:
        print("Sphinx could not understand audio")
    except sr.RequestError as e:
        print("Sphinx error; {0}".format(e))
Ejemplo n.º 19
0
def create_sounds(sounds: list):
    for sound in sounds:
        # NOTE: It's not possible to decorate a lambda function with arguments, so this approach is used.
        # Sound object is initialized when assigned to 's', avoiding parent variable search.
        # Don't -> lambda m: Class.method()
        # Do -> lambda m, o=Class(): o.method()
        #pylint: disable=cell-var-from-loop
        func = {
            'active':
            True,
            'function':
            lambda _, s=AudioPlayer(os.path.join(SOUNDS_PATH, sound)):
            play_sound(s),
            'commands': [f'!{sound[:-4].lower()}'],
            'regexp':
            '',
            'access':
            0
        }
        BOT.handlers.append(func)
        LOGGER.debug('Sound: %s created.', func['commands'][0])
Ejemplo n.º 20
0
def dostep():
    print(
        Fore.CYAN +
        '1 - Web\n2 - Gry\n3 - Produkty w Sklepie u MrEsxej`a\n4 - Notatki\n5 - Play Audio\n6 - Piwnica\n7 - Autorzy\n8 - Waluty\n9 - Ustawienia\n10 - Exit'
    )
    button = input('>')
    if button == '1':
        os.system('cls')
        print(Fore.CYAN + 'Wpisz URL lub napisz quit aby wyjść:')
        url = input('>')
        if url == 'quit':
            os.system('cls')
            dostep()
        else:
            webbrowser.open(url)
            Back()
    elif button == '2':
        os.system('cls')
        print(Fore.CYAN + 'Gry:')
        path = 'Games/'

        files = os.listdir(path)

        for f in files:
            print(f)
        game_path = input('>')
        try:
            os.startfile(f'Games\{game_path}')
        except:
            print(Fore.RED +
                  "Plik nie dostępny! sprawdź  nazwę i uprawnienia.")
        Back()
    elif button == '3':
        os.system('cls')
        print(Fore.CYAN + info.sklep)
        Back()
    elif button == '4':
        os.system('cls')
        print(Fore.CYAN + 'Notatki:')
        path = 'Notes/'

        files = os.listdir(path)

        for f in files:
            print(f)
        file = input('>')
        try:
            ofile = open('Notes/' + file, 'r')
            print(ofile.read())
            ofile.close()
        except:
            print(Fore.RED +
                  "Plik nie dostępny! sprawdź  nazwę i uprawnienia.")

        #ofile = open('Notes/' + file, 'w')
        #write = input('>')
        #ofile.write(write)

        Back()
    elif button == '5':
        os.system('cls')
        print(Fore.CYAN + 'audio:')
        path = 'Audio/'
        files = os.listdir(path)
        for f in files:
            print(f)
        sound = input('>')
        try:
            AudioPlayer('Audio/' + sound).play(block=False)
        except:
            print(Fore.RED +
                  "Plik nie dostępny! sprawdź  nazwę i uprawnienia.")
        Back()
    elif button == '6':
        os.system('cls')
        print('Zapraszamy!')
        webbrowser.open('https://discord.gg/2wWh8ygKMb')
        Back()
    elif button == '7':
        os.system('cls')
        print(Fore.CYAN + info.autors)
        Back()
    elif button == '8':
        os.system('cls')
        print(
            Fore.CYAN +
            '100 tynkcoin = 1 Marek\n100 Marków = 1 Super-Matek\n100 Super-Marków = 1 Ultra-Marek\n100 Ultra-Marków = 1 Super-Ultra-Marek\n100 Super-Ultra-Marków = 1 Super-Duper-Ultra-Marek'
        )
        Back()
    elif button == '9':
        os.system('cls')
        print(Fore.CYAN + '1 - Wyjdź\n2 - Zmień Hasło\n3 - Resetuj Ustawienia')
        num = input('>')
        if num == '1':
            dostep()
        elif num == '2':
            os.system('cls')
            print(Fore.CYAN + 'Wpisz nowe Hasło')
            new = input('>')
            newa = new.encode()
            newb = hashlib.sha256(newa)
            new_json = '{\n    "Password": "******"\n}'

            with open('Setting.json', 'w') as myfile:
                myfile.write(new_json)
        elif num == '3':
            os.system('cls')
            print(Fore.CYAN + 'Wpisz hasło:')
            has = input('>')
            b = has.encode()
            c = hashlib.sha256(b)
            if c.hexdigest() == str(obj['Password']):
                print(Fore.RED + 'Ustawienia Zresetowane')
                resetjson = '{\n    "Password": "******"\n}'
                with open('Setting.json', 'w') as myfile:
                    myfile.write(resetjson)
        else:
            os.system('cls')
            print(Fore.RED + 'ERROR')
            Back()
    elif button == '10':
        print(Fore.RED + 'DOWIDZENIA!')
        time.sleep(1)
        exit()
    else:
        os.system('cls')
        print(Fore.RED + 'ERROR')
        dostep()
randomcardlist = []

wrongcard = False

playerturndone = False
comturndone = False

if playornoplay == "yes":

    time.sleep(1)
    os.system("clear")

    #This means the game will run
    print("then lets play!\n")
    #Game rules
    rulessong = AudioPlayer("rules song.mp3")
    rulessong.play()

    print("Here is how to play this game:\n")
    print(
        "there will be six cards you can only pick 3 and the com player will pick 3\n"
    )
    print(
        "you pick the three cards and win by luck. you might have good luck meaning you win\n"
    )
    print("or you have bad luck and you lose!\n")
    print(
        "press key 1 to 6 to choose a card for each turn you get and then press enter\n"
    )
    print("when you select one card you cant use it again.\n")
    print(
Ejemplo n.º 22
0
from audioplayer import AudioPlayer

# Playback stops when the object is destroyed (GC'ed), so save a reference to the object for non-blocking playback.
AudioPlayer("hello.mp3").play(block=True)
Ejemplo n.º 23
0
from audioplayer import AudioPlayer
import os

mp3 = os.path.join(os.path.dirname(__file__), 'audio', 'toquesuave.mp3') # ringtone by felipebbrusso'

p = AudioPlayer(mp3)

print('Playing {} in loop'.format(p.fullfilename))
p.play(block=False, loop=True)

input('Press Enter to pause ')
p.pause()

input('Press Enter to resume ')
p.resume()

input('Press Enter to set volume to 1% ')
p.volume = 1

input('Press Enter to set volume to 10% ')
p.volume = 10

input('Press Enter to set volume to 50% ')
p.volume = 50

input('Press Enter to set volume to 100% ')
p.volume = 100

input('Press Enter to stop ')
p.stop()
Ejemplo n.º 24
0
            results_available = True
        window["extra_info"].update(
            "\n \n \n \n \n \n \n \n \n \n \n \n \n \n Click on a show episode for extra info"
        )
    if event == 'results':
        if results_available:
            list_vals = window["results"].get_list_values()
            pos = list_vals.index(values['results'][0])
            (show_name, episode_name) = show_and_eps[pos]

            window["extra_info"].update("")
            query_result.print_description(cprint, show_name, episode_name,
                                           spotify)
            query_result.update_preview(show_name, episode_name, spotify)

            image_elem.update(data=get_img_data(
                "img/tmp.jpg", maxsize=(200, 200), first=True))

            window["extra_info"].set_vscroll_position(0)

    if event == 'Play':
        player = AudioPlayer("img/tmp.mp3")
        player.play()

    if event == 'Pause':
        player.stop()

    if event == 'Open on Spotify':
        query_result.openurl()

window.close()
Ejemplo n.º 25
0
 def play_sound_local(self):
     audio_path = self.option.get('active')
     audio_path = os.path.join(self.recording_path, audio_path) + ".wav"
     self.ap = AudioPlayer(audio_path)
     self.ap.play(block=False)
Ejemplo n.º 26
0
class GameCard(Scatter):
    '''
    Swipeable game card with word to guess

    Attributes
    ----------
    start_position : tuple(float)
        default position of the card at the center of the screen
    title : StringProperty
        word on the card to guess
    audio_player : AudioPlayer
        instance of `AudioPlayer` to play sound when swipe
    is_first : bool
        is card first(default) or not
    round_screen : RoundScreen
        instance of active `RoundScreen` class

    Methods
    -------
    on_touch_up(touch):
        kivy method

    card_disappear_animation(to_top):
        dissapear card animation

    remove_self(point):
        remove card after dissapear animation
    '''
    start_position = None
    title = StringProperty()
    audio_player = AudioPlayer()
    is_first = BooleanProperty(False)

    def __init__(self, round_screen, **kwargs):
        super().__init__(**kwargs)
        self.round_screen = round_screen

    def on_kv_post(self, _):
        '''
        Kivy method overriden to assign start position
        '''
        def assign_start_position(pos):
            self.start_position = pos

        Clock.schedule_once(lambda _: assign_start_position(self.pos))

    def on_touch_up(self, touch):
        '''
        Kivy method overriden to handle swipe
        '''
        super().on_touch_up(touch)
        try:
            # relative bias
            bias = (self.pos[1] - self.start_position[1]) / self.size[1]

            # swipe a card a half size up
            if bias > .5:
                self.card_disappear_animation(True)
                if not self.is_first:
                    self.audio_player.play_sound('plus')
            # swipe down
            elif bias < -.5:
                self.card_disappear_animation(False)
                if not self.is_first:
                    self.audio_player.play_sound('minus')
            # otherwise return start position
            else:
                Animation(pos=self.start_position, d=0.1).start(self)
        except (ZeroDivisionError, TypeError):
            pass

    def card_disappear_animation(self, to_top):
        '''
        Animate card dissapear when swipe

        Parameters
        ----------
        to_top : bool
            is swipe to top or not
        '''
        # to top or bottom of layout
        destination_pos = (self.parent.width / 2, self.parent.y +
                           (self.parent.height if to_top else -self.height))
        anim = Animation(pos=destination_pos, scale=.5, d=.1)
        anim.bind(on_start=lambda anim, wid: self.round_screen.generate_card())
        anim.bind(on_complete=lambda anim, wid: self.remove_self(to_top))
        anim.start(self)

    def remove_self(self, point):
        '''
        Remove self from the screen

        Parameters
        ----------
        point : int
            point for guessing word
        '''
        try:
            self.round_screen.remove_current_card(self, point)
        except AttributeError:
            pass
Ejemplo n.º 27
0
    global total, killed, level, time
    total = killed = 0
    level = 1
    time = 1000
    game.start_timer(time)
    timer()
    mosquito_sound.play()
    mosquito_sound.volume = 30


game = Board(10, 10)
game.title = "Kill the mosquito"
game.cursor = "crosshair"
game.cell_size = 50
game.margin = 0
# From: https://opengameart.org/content/good-night
game.background_image = "mountainsatnight.png"
game.on_mouse_click = mousefn
game.on_key_press = tecladofn
game.on_start = start
game.on_timer = timer
game.create_output(background_color="#606163", color="pink", font_size=12)

sounds_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'sounds')
mosquito_sound = AudioPlayer(
    os.path.join(sounds_dir, 'salamisound-2276970-mosquito-or-similar-in.mp3')
)  # From https://www.salamisound.com/2276970-mosquito-or-similar-in
# From https://opengameart.org/content/95-sfx-pack-beats-warrior-nian
attack_sound = AudioPlayer(os.path.join(sounds_dir, 'snd_boss_attack_t2.mp3'))
game.show()
Ejemplo n.º 28
0
def playSoundNotify():
    AudioPlayer('sounds/default.mp3').play(block=True)
Ejemplo n.º 29
0
 def new_sound(_, sound=AudioPlayer(os.path.join(SOUNDS_PATH, sound))):
     play_sound(sound)
Ejemplo n.º 30
0
def timerFired(app):
    app.timer += 10
    if (app.isStarted == False):
        insABSwitch(app)
    elif (app.isStarted == True):
        if (app.isInsC == True):
            if (app.timer == 100):
                voiceIns = gTTS(text=app.insC, lang=app.language, slow=False)
                voiceIns.save("voiceInstruction1.mp3")
                #os.system("omxplayer voiceInstruction1.mp3")
                AudioPlayer("voiceInstruction1.mp3").play(block=True)
            if (app.timer == 200
                ):  #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                app.isInsC = False
                app.isInsD = True
                app.timer = 0
        elif (app.isInsD == True):
            if app.timer == 100:
                AudioPlayer("voiceInstruction2.mp3").play(block=True)
            if (app.timer >= 500 and app.timer % 200 == 0):
                voiceIns = gTTS(text=app.insD, lang=app.language, slow=False)
                voiceIns.save("voiceInstruction2.wav")
                speechRecognition(app)
                if len(app.speechRecognized
                       ) >= 9 and app.speechRecognized[0:9] == "i'm ready":
                    app.isInsE = True
                    app.isInsD = False
                    app.timer = 0
                    ser.write("d".encode('utf-8'))
                else:
                    AudioPlayer("errorMessage.mp3").play(block=True)
        elif (app.isInsE == True):

            if (app.timer == 100):
                voiceIns = gTTS(text=app.insE, lang=app.language, slow=False)
                voiceIns.save("voiceInstruction.wav")
                AudioPlayer("voiceInstruction3.mp3").play(block=True)
            if (app.timer == 200):
                app.isInsE = False
                app.isInsF = True
                app.timer = 0
                app.camera.start_preview(alpha=240)
        elif (app.isInsF == True):
            if (app.timer == 50): ser.write("f".encode('utf-8'))
            if app.timer % 50 == 0:
                app.countDown -= 1
            if app.timer == 6000:
                app.isInsG = True
                app.isInsF = False
                app.timer = 0
                app.camera.stop_preview()
                ser.write("g".encode('utf-8'))
        elif (app.isInsG == True):
            if app.timer == 100:
                AudioPlayer("voiceInstruction4.mp3").play(block=True)
            if (app.timer >= 1000 and app.timer % 200 == 0):
                voiceIns = gTTS(text=app.insD, lang=app.language, slow=False)
                voiceIns.save("voiceInstruction2.wav")
                speechRecognition(app)
                if len(app.speechRecognized
                       ) >= 8 and app.speechRecognized[0:7] == "mission":
                    app.isInsH = True
                    app.isInsG = False
                    app.timer = 0
                    ser.write("g".encode('utf-8'))
                else:
                    AudioPlayer("errorMessage.mp3").play(block=True)
        elif (app.isInsH == True):
            if (app.timer == 100):
                ser.write("h".encode('utf-8'))
                voiceIns = gTTS(text=app.insE, lang=app.language, slow=False)
                voiceIns.save("voiceInstruction.wav")
                AudioPlayer("voiceInstruction5.mp3").play(block=True)
            if (app.timer == 1000):
                appStarted(app)

    moveDemo(app)