def _mouse_up(self, event):
     sa.stop_all()
     self.canvas.delete('all')
     self.canvas.create_text(self.canvas.winfo_width()//2, self.canvas.winfo_height(),
                             anchor = 's', text="Press 'Esc' to Quit.",
                             font = ('Helvetica', 32, 'bold'), fill='white')
     self.prev_mouse_event = None
def toggle_flag():
    sa.stop_all()
    stop_flag.set(not stop_flag.get())
    if stop_flag.get() is True:
        toggle_button.config(bg="#728C00", fg="white", text="Poly")
    else:
        toggle_button.config(bg="#000000", fg="white", text="Mono")
Exemplo n.º 3
0
    def run(self):
        musicfile = sa.WaveObject.from_wave_file(self.file_name)
        musicfile.play()
        Direction.direction_p_1.value = 0
        while Direction.direction_p_1.value != 7:
            num = int(self.num)
            h = abs(dct(self.wave_data[0][self.nframes - num:self.nframes - num + self.N]))
            h = [min(self.HEIGHT, int(i ** (1 / 2.5) * self.HEIGHT / 100)) * self.amplifier for i in h]

            self.frames = [h] + self.frames

            """
            i = 0
            for f in self.frames:
                if i < self.cube_size:
                    api.change_face(api.Face.FRONT, i, util.construct_2D_audio_frame(self.cube_size, f))
                    i += 1
                else:
                    self.frames.remove(f)
                    """

            for x in range(self.cube_size):
                api.change_face(api.Face.FRONT, self.cube_size - 1 - x,
                                util.construct_2D_audio_frame(self.cube_size, h, x))

            self.num -= (1 / self.fps) * self.framerate

            if self.num < 0:
                self.finished = True

            time.sleep(1 / (self.fps * 2.2))

        sa.stop_all()
        self.finished = True
        Direction.direction_p_1.value = 0
Exemplo n.º 4
0
async def event_raw_data(data):

    # Raid Detection
    if FE_SHOUTOUT and dat.raid_autoso:
        if not "PRIVMSG" in data:
            if "USERNOTICE" in data and "msg-id=raid" in data:
                mname = re.search('msg-param-displayName\=(.+?);', data)
                mvcnt = re.search('msg-param-viewerCount\=([0-9]+?);', data)
                mid = re.search('msg-param-login\=(.+?);', data)
                if mname.group(1) == mid.group(1):
                    print("[RAID] " + mname.group(1) + " raiding with " +
                          mvcnt.group(1) + " viewers!!")
                else:
                    print("[RAID] " + mname.group(1) + "(" + mid.group(1) +
                          ") raiding with " + mvcnt.group(1) + " viewers!!")

                if dat.channel != None:
                    dlytime = 0.0
                    for idx in range(5):
                        if dat.threads[idx] == None or dat.threads[
                                idx].is_alive() == False:
                            rn = int(mvcnt.group(1))
                            dlytime = 45.0 * (rn / (30.0 + abs(rn)))
                            dat.so_args[idx] = mid.group(1)
                            dat.threads[idx] = threading.Timer(
                                dlytime,
                                dat.sendShoutout,
                                args=(dat.so_args[idx], ))
                            dat.threads[idx].start()
                            break
                    if dlytime > 30.0:
                        dat.sendShoutout(mid.group(1), mname.group(1))
                if dat.raid_beep:
                    simpleaudio.stop_all()
                    gRAIDBeep.play()
Exemplo n.º 5
0
    def play_loaded_audio(self, event):
        import numpy as np

        player_button = str(event.widget).split('.')[-1]

        if player_button == 'play_unfiltered':
            selected_audio_file = self.audio_file
            button_label = self.play_button_text
        elif player_button == 'play_filtered':
            selected_audio_file = self.filtered_audio_file
            button_label = self.filtered_play_button_text
        else:
            selected_audio_file = self.human_hearing
            button_label = self.hh_play_button_text

        data = (selected_audio_file * 32767 / max(abs(selected_audio_file)))
        data = data.astype(np.int16)

        if event.widget['text'] == 'Play':
            self.play_button_text.set('Play')
            self.filtered_play_button_text.set('Play')
            self.hh_play_button_text.set('Play')
            button_label.set('Stop')
            sa.stop_all()
            play_obj = sa.play_buffer(data, 1, self.bytes_per_sample,
                                      self.rate)
        else:
            button_label.set('Play')
            sa.stop_all()
        return
Exemplo n.º 6
0
    def emu_event(self):
        self.emu.cpu_tick()

        for err in self.emu.error_log:
            print( str(err[0]) + ": " + err[1] )
            if err[0] is EmulationError._Fatal:
                self.fatal = True
            self.emu.error_log = []

        if self.emu.draw_flag:
            self.emu.draw_flag = False

            if not self.antiflicker.get():
                self.draw()
            else:
                cur_screen = ''
                for i,pix in enumerate(self.emu.graphics()):
                    cur_screen += '1' if pix else '0'
                cur_screen = int(cur_screen,2)

                if ( ( self.prev_screen ^ cur_screen ) & self.prev_screen ) != ( self.prev_screen ^ cur_screen ):
                    self.draw()
                self.prev_screen = cur_screen

        if not self.fatal:
            self.root.after(self.run_time, self.emu_event)
        else:
            self.menubar.add_cascade(label="Fatal Error has occured!", menu=Menu(self.menubar, tearoff=0))
            sa.stop_all()
Exemplo n.º 7
0
def playAudio(wav_path):
    simpleaudio.stop_all()
    wav_path = wav_path.replace(os.sep, '/')
    try:
        wav_obj = simpleaudio.WaveObject.from_wave_file(wav_path)
        play_obj = wav_obj.play()
    except:
        errtxt = "Error: Cannnot play the file"
        sg.popup_ok(errtxt)
Exemplo n.º 8
0
 def _check(cls):
     wave_obj_1 = _gwo("c.wav")
     wave_obj_2 = _gwo("e.wav")
     wave_obj_3 = _gwo("g.wav")
     wave_obj_1.play()
     wave_obj_2.play()
     wave_obj_3.play()
     sleep(0.5)
     sa.stop_all()
     sleep(3)
Exemplo n.º 9
0
 def _check(cls):
     wave_obj_1 = _gwo("c.wav")
     wave_obj_2 = _gwo("e.wav")
     wave_obj_3 = _gwo("g.wav")
     wave_obj_1.play()
     wave_obj_2.play()
     wave_obj_3.play()
     sleep(0.5)
     sa.stop_all()
     sleep(3)
Exemplo n.º 10
0
def play_sound(data, fs):
    """
    Uses Sounddevice to produce sound.

    =====================================
    :param data: numpy array
    :param fs: Sample Rate
    """
    sa.stop_all()
    sa.play_buffer(data, len(data.shape), 2, fs)
    time.sleep(1)
Exemplo n.º 11
0
    def do_test(self, sound):
        sample = self.samples.get(sound)
        if sample is not None:
            play_obj = sa.play_buffer(sample, self.nchannels, self.sampwidth,
                                      self.framerate)

            time.sleep(2)
            sa.stop_all()
            print("Done")
        else:
            print("No sample loaded")
Exemplo n.º 12
0
def reset(addr):
    # stop video if playing
    while videoProcessHandle.poll() is None:
        videoProcessHandle.kill()

    # stop all audio
    saudio.stop_all()

    # normal boot process
    setup()
    main()
Exemplo n.º 13
0
    def timers_event(self):
        if (self.emu is not None) and (self.fatal is False):
            if self.audio_on:
                if self.emu.sound_timer_register != 0:
                    self.wave_obj.play()
                else:
                    sa.stop_all()

            self.emu.sound_timer_register -= 1 if self.emu.sound_timer_register != 0 else 0
            self.emu.delay_timer_register -= 1 if self.emu.delay_timer_register != 0 else 0

        self.root.after(Nacho.TIMER_REFRESH, self.timers_event)
Exemplo n.º 14
0
def clear_ambients():

    set = services.database.get_meta("ambients_duration")
    if(int(set.value) > 0):

        clear_time = set.added + timedelta(minutes=int(set.value))  

        if(clear_time > datetime.now()):
            set_ambients("none",0) 
            set_lighting_override(0)
            set_ambients_status("off")
            simpleaudio.stop_all()
Exemplo n.º 15
0
async def event_raw_data(data):
    if DEBUG:
        print("[RAW]", data)

    # Raid Detection
    if not "PRIVMSG" in data:
        if "USERNOTICE" in data and "msg-id=raid" in data:
            mname = re.search('msg-param-displayName\=(.+?);', data)
            mvcnt = re.search('msg-param-viewerCount\=([0-9]+?);', data)
            mid = re.search('msg-param-login\=(.+?);', data)
            print("[RAID]", mname.group(1), "raiding with", mvcnt.group(1),
                  "viewers!!")
            if dat.obsConnected:
                dat.ws.call(
                    obsrequests.SetCurrentScene("raid"))  # OBS scene change
            if dat.raid_autoso:
                print("[RAID] " + mname.group(1) + "(" + mid.group(1) +
                      ") raiding with " + mvcnt.group(1) + " viewers!!")
                if dat.channel != None:
                    if SO_SELF:
                        if USE_TAPI:
                            ci = dat.getChannelInfo(
                                dat.getUIDfromName(mid.group(1)))
                            if ci == None:
                                await dat.channel.send("[shoutout] 不明なユーザー名です")
                            else:
                                if ci['broadcaster_name'] != mname.group(1):
                                    name = ci[
                                        'broadcaster_name'] + "(" + mname.group(
                                            1) + ")"
                                else:
                                    name = mname.group(1)
                                await dat.channel.send(
                                    f"§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§  - - - - - Please check this awesome streamer!! - - - - - - - この素晴らしい配信者もチェックしてください! - -  {name} : https://twitch.tv/{mid.group(1)} 最近の配信 Recent stream : {ci['game_name']} - {ci['title']}  §=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§"
                                )
                        else:
                            if mname.group(1) != mid.group(1):
                                name = mname.group(1) + "(" + mid.group(
                                    1) + ")"
                            else:
                                name = mid.group(1)
                            await dat.channel.send(
                                f"§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§  - - - - - Please check this awesome streamer!! - - - - - - - この素晴らしい配信者もチェックしてください! - -  {name} : https://twitch.tv/{mid.group(1)}  §=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§=§"
                            )
                    else:
                        await dat.channel.send("!so " + mid.group(1))
                else:
                    print("dat.channel is None.")
            if SOUND and dat.raid_beep:
                simpleaudio.stop_all()
                gBeep.play()
Exemplo n.º 16
0
    def play(cls, filename, audio_format="mp3", wait=False, stop=False):
        """Play audio file."""

        if stop:
            simpleaudio.stop_all()

        seg = AudioSegment.from_file(filename, audio_format)
        playback = simpleaudio.play_buffer(seg.raw_data,
                                           num_channels=seg.channels,
                                           bytes_per_sample=seg.sample_width,
                                           sample_rate=seg.frame_rate)

        if wait:
            playback.wait_done()
    def _play_sound(self, x_pos, y_pos):
        # calculate frequency of "piano key" based on y_pos
        pkey = np.floor(88 * (self.canvas.winfo_height() - (y_pos + 1)) / self.canvas.winfo_height() + 1)
        frequency =  440 * 2**((pkey - 49)/12) # 440Hz is key #49 on a piano

        # calculate volume based on x_pos
        volume = x_pos / self.canvas.winfo_width()

        # generate and play audio samples
        audio = np.round(np.sin(frequency * TIME_VECT * 2 * np.pi))
        audio *= volume * 32767
        audio = audio.astype(np.int16)
        sa.stop_all()
        sa.play_buffer(audio, 1, 2, SAMPLE_RATE)
Exemplo n.º 18
0
    def toggle_playback(self):
        if self.playing:
            sa.stop_all()

        else:
            loop = self.render_loop(self, self.current_sound)
            self.playing = True
            play_obj = sa.play_buffer(loop, self.nchannels, self.sampwidth,
                                      self.framerate)
            while self.playing:
                if not play_obj.is_playing():
                    play_obj = sa.play_buffer(loop, self.nchannels,
                                              self.sampwidth, self.framerate)
                else:
                    continue
Exemplo n.º 19
0
    def play(self, data):
        """
        plays the result in app player
        """
        self.logger.debug("Playing .. ")

        if self.channels[data] is not None:
            sa.stop_all()
            sa.play_buffer(self.channels[data], 1, 2, self.rate)
            sleep(1)

        else:
            self.logger.debug("Fail to play")
            self.show_message("Warning", "Load A file First", QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Warning)
            pass
Exemplo n.º 20
0
def play_on_host(music):
    print("play on host")
    music = Music.query.filter_by(title=music.split(".")[0]).first()
    if not music:
        return jsonify({'msg': 'data is empty'})
    simpleaudio.stop_all()
    try:
        print("before try")
        music = AudioSegment.from_file(music.link)
        print("muisc_found")
        simpleaudio.play_buffer(music.raw_data,num_channels=music.channels,bytes_per_sample=music.sample_width,sample_rate=music.frame_rate)
        print("simple:audio")
        return jsonify({'msg': 'music is playing'})
    except:
        return jsonify({'msg', 'error'})
    return jsonify({'msg': 'play_on_host'})
Exemplo n.º 21
0
def main():
    angerCount = 0
    args = sys.argv
    picturePath = './pic/'

    try:
        f = sf.SoundFile(args[1])
    except Exception as e:
        viewUsecase()

    if len(sys.argv) < 3:
        viewUsecase()

    if int(args[2]) < 1 or int(args[2]) > 100:
        viewUsecase()

    waveToPng(args[1], "target.png")
    seconds = len(f) / f.samplerate
    print('seconds = ', seconds)

    bf = cv2.BFMatcher(cv2.NORM_HAMMING)
    detector = cv2.ORB_create()
    (target_kp, target_des) = calc_kp_and_des("target.png", detector)

    try:
        while True:
            recordSound("now.wav", seconds / 2)
            waveToPng("now.wav", "now.png")
            try:
                (comparing_kp,
                 comparing_des) = calc_kp_and_des("now.png", detector)
                matches = bf.match(target_des, comparing_des)
                dist = [m.distance for m in matches]
                ret = sum(dist) / len(dist)
            except cv2.error:
                ret = 100000

            print(ret, ' match!')
            if float(args[2]) > ret:
                playInvertSound(args[1])
                angerCount = angerCount + 1
                tprint(str(angerCount) + ' anger!', "random")
            else:
                simpleaudio.stop_all()

    except KeyboardInterrupt:
        print('Exit.')
Exemplo n.º 22
0
    def close_start(self):
        # Make the Players list from the entries
        self.players = []
        self.players_ref = {}
        num = app.getScale('nump_scale')

        for i in range(num):
            j = i + 1
            entry = 'player_{}'.format(j)
            name = app.getEntry(entry)
            self.players.append(name)
            self.players_ref[name] = Player(name)

        beats.stop_all()
        self.started = True
        app.destroySubWindow('New Game')
        app.show()
        self.table_layout(num)
Exemplo n.º 23
0
async def event_raw_data(data):
    if dat.ready:

        if DEBUG:
            print("[RAW]", data)

        # Raid Detection
        if not "PRIVMSG" in data:
            if "USERNOTICE" in data and "msg-id=raid" in data:
                mname = re.search('msg-param-displayName\=(.+?);', data)
                mvcnt = re.search('msg-param-viewerCount\=([0-9]+?);', data)
                mid = re.search('msg-param-login\=(.+?);', data)
                print("[RAID] " + mname.group(1) + "(" + mid.group(1) +
                      ") raiding with " + mvcnt.group(1) + " viewers!!")
                if dat.channel != None:
                    await dat.channel.send(
                        f"Please check this awesome streamer!! この素晴らしい配信者もチェックしてください! {mid.group(1)} : https://twitch.tv/{mid.group(1)}"
                    )  # Raid時のshoutout
                simpleaudio.stop_all()
                gBeep.play()
Exemplo n.º 24
0
    def play(self, playlist_name, callback, offset=0):
        simpleaudio.stop_all()

        playlist = Playlist(PLAYLIST_DIR, playlist_name)
        self.current_playlist = playlist

        songs = cycle(playlist.songs)

        for song in islice(songs, offset, None):
            if self.current_playlist is not playlist:
                break

            if not self._download_exists(song):
                print(f'Downloading {song}')
                callback.on_downloading_song(song)
                self.downloader.download(song)

            print(f'Playing {song}')
            callback.on_song_started(song)
            self._play_audio(song)
Exemplo n.º 25
0
def create_alert(nb_alarms, old_nb_alarms, n_clicks):
    if n_clicks % 2 == 0:
        sound = False
    else:
        sound = True
    if sound:
        wave_obj = sa.WaveObject.from_wave_file("assets/alert-sound.wav")
    else:
        wave_obj = sa.WaveObject.from_wave_file("assets/alert-no-sound.wav")

    if nb_alarms == 0:
        sa.stop_all()
        return [], old_nb_alarms
    elif nb_alarms <= old_nb_alarms:
        sa.stop_all()
        try:
            wave_obj.play()
        except SimpleaudioError:
            pass
        return dbc.Alert('Warning, alarm(s)!', color='warning', dismissable=True, is_open=True), old_nb_alarms
    else:
        sa.stop_all()
        try:
            wave_obj.play()
        except SimpleaudioError:
            pass
        return dbc.Alert('Warning, new alarm(s)!', color='danger', dismissable=True, is_open=True), nb_alarms
Exemplo n.º 26
0
    def render_loop(self, sound, pattern):
        audio = np.zeros((self.pattern_nsamples), dtype=np.int16)
        sample = self.samples.get(sound)
        if sample is None:
            raise Exception("Error")
        sample_length = len(sample)
        sample = sample[:len(audio)]

        for ind, tick in enumerate(pattern):
            if tick == 1:
                tickpos = self.loop_markers[ind]
                audio[tickpos:sample_length + tickpos] += sample

            else:
                continue

        #audio *= 32767 / np.max(np.abs(audio))
        audio = audio.astype(np.int16)
        sa.play_buffer(audio, self.nchannels, self.sampwidth, self.framerate)
        time.sleep(self.pattern_duration)
        sa.stop_all()
        print("Loop Rendered")
        return audio
Exemplo n.º 27
0
async def event_message(message):
    if dat.fQuit:
        # bot.close() # will be impliment on TwitchIO 2.0
        exit()
    if dat.channel == None:
        dat.channel = message.channel

    if not dat.isInDenylist(message.author.name):
        if dat.isNewViewer(message.author.name):

            # ビューワーリストに追加:append user to list
            dat.appendViewer(message.author.name)

            # 通知音再生:play beep sound
            if SOUND:
                simpleaudio.stop_all()
                gBeep.play()

            # 有効時に登録したキーを入力:type registered key if enabled
            if dat.motionEN:
                keyboard.press_and_release(dat.motionkey)

            # 表示名取得:get display-name
            disp_name = re.search('display-name\=(.+?);',
                                  message.raw_data).group(1)

            # メッセージを表示:print message
            if disp_name == None:
                print(f'[New Viewer] {message.author.name} is coming!'
                      )  # to console
            else:
                print(
                    f'[New Viewer] {disp_name}({message.author.name}) is coming!'
                )  # to console

    # If you override event_message you will need to handle_commands for commands to work.
    await bot.handle_commands(message)
Exemplo n.º 28
0
async def event_message(message):
    if dat.fQuit:
        # bot.close() # will be impliment on TwitchIO 2.0
        exit()
    if dat.channel == None:
        dat.channel = message.channel

    if dat.isAdtarget(message.author.name):
        dat.sendShoutout(message.author.name)
        dat.AdDone(message.author.name)

    if not dat.isInDenylist(message.author.name):
        if dat.isNewViewer(message.author.name):

            # ビューワーリストに追加:append user to list
            dat.appendViewer(message.author.name)

            # 通知音再生:play beep sound
            simpleaudio.stop_all()
            gNEWBeep.play()

            # 表示名取得:get display-name
            disp_name = re.search('display-name\=(.+?);',
                                  message.raw_data).group(1)

            # メッセージを表示:print message
            if disp_name == None:
                print(f'[New Viewer] {message.author.name} is coming!'
                      )  # to console
            else:
                print(
                    f'[New Viewer] {disp_name}({message.author.name}) is coming!'
                )  # to console

    # If you override event_message you will need to handle_commands for commands to work.
    await bot.handle_commands(message)
Exemplo n.º 29
0
    def play_audio(self, wave_file):
        if self.progress_timer:
            self.root.after_cancel(self.progress_timer)
        sa.stop_all()

        try:
            fs, audio_data = wav.read(wave_file)
        except:
            print("can not read {}".format(wave_file))
            return

        play_zone = self.plotter_.get_play_time_zone()

        fs, audio_data = wav.read(wave_file)
        if play_zone:
            start_position = int(play_zone.start * fs)
            end_position = int(play_zone.end * fs)
            self.play_time = play_zone.start
            self.play_end_time = play_zone.end
        else:
            start_position = 0
            end_position = audio_data.shape[0]
            self.play_time = 0
            self.play_end_time = audio_data.shape[0] / fs

        # self.timer = self.plotter_.get_figure().canvas.new_timer(interval = 100, callbacks=[(self.update_play_progress, (1, ), {'a': 3}),])
        # self.timer.start()
        # self.plotter_.plot_progress(self.play_time)

        sa.play_buffer(audio_data[start_position:end_position],
                       num_channels=1,
                       bytes_per_sample=2,
                       sample_rate=fs)

        self.wait_id = self.root.after(Pypraat.UPDATE_PROGRESS_INTERVAL_MS,
                                       self.update_play_progress)
Exemplo n.º 30
0
def main():

    # Display the start menu
    display_start_menu()
    # Add each item to a random room
    random_generate_items()
    # Main game loop
    while True:
        if Players["Doc"]["escape"] == True:
            print(endings["escape"])
            sa.stop_all()
            break

        elif Players["Doc"]["alive"] == False:
            print(endings["die"])
            sa.stop_all()
            break

        elif Players["Hannibal the cannibal"]["alive"] == False:
            print(endings["live"])
            sa.stop_all()
            break

        else:
            if rooms["Reception"]["phone"] == False:
                global phone_used
                phone_used = phone_used + 1
                if phone_used > 3:
                    Players["Doc"]["escape"] = True

            # Display game status (room description, inventory etc.)
            print_room(Players["Doc"]["current_room"])
            print_inventory_items(Players["Doc"]["inventory"])

            # Show the menu with possible actions and ask the player
            command = menu(Players["Doc"]["current_room"]["exits"],
                           Players["Doc"]["current_room"]["items"],
                           Players["Doc"]["inventory"])
            # Execute the player's command
            if execute_command(command) == False:
                break
Exemplo n.º 31
0
 def stop_all(self) -> None:
     """
     Stops all sounds from playing
     """
     sa.stop_all()
Exemplo n.º 32
0
 def stop_all_sounds(self):
     if self.type == 'pygame':
         pygame.mixer.stop()
     elif self.type == 'simpleaudio':
         simpleaudio.stop_all()
     return