Can I stop listening for audio on keyboard press?
I tried altering the record function (in init.py) like this:
def record(self, source, duration=None, offset=None):
"""
Records up to ``duration`` seconds of audio from ``source`` (an ``AudioSource`` instance) starting at ``offset`` (or at the beginning if not specified) into an ``AudioData`` instance, which it returns.
If ``duration`` is not specified, then it will record until there is no more audio input.
"""
assert isinstance(source, AudioSource), "Source must be an audio source"
assert source.stream is not None, "Audio source must be entered before recording, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement?"
frames = io.BytesIO()
seconds_per_buffer = (source.CHUNK + 0.0) / source.SAMPLE_RATE
elapsed_time = 0
offset_time = 0
offset_reached = False
while True: # loop for the total number of chunks needed
if offset and not offset_reached:
offset_time += seconds_per_buffer
if offset_time > offset:
offset_reached = True
buffer = source.stream.read(source.CHUNK)
if len(buffer) == 0: break
if offset_reached or not offset:
elapsed_time += seconds_per_buffer
if keyboard.read_key() == "p":
print("\nYou pressed p")
break
frames.write(buffer)
frame_data = frames.getvalue()
frames.close()
return AudioData(frame_data, source.SAMPLE_RATE, source.SAMPLE_WIDTH)
And calling it from my main script like this:
def Main():
r = sr.Recognizer()
try:
with sr.Microphone() as source:
print("Listening....")
audio = r.record(source)
print("Recognizing....")
r.adjust_for_ambient_noise(source)
text = r.recognize_google(audio)
print(text.lower())
if "lock computer" in text.lower():
ctypes.windll.user32.LockWorkStation()
elif "joke" in text.lower():
joke = pyjokes.get_joke()
speak(joke)
except Exception as e:
print(e)
Main()
This listen to the audio and stops listening when I press p but does not recognize it
I figured it out, I saved the input file and saw that there was no audio in it so google could not reognize it.
The error was in this block:
if keyboard.read_key() == "p":
print("\nYou pressed p")
break
I changed this to:
if keyboard.read_key() == "p":
print("\nYou pressed p")
pressed = True
break
And copied the listen function and dublicated it, changed its name to listen1
And now when I press P it stops listening and recognizing is also working.
Related
As a new programmer, I'm trying to create a Python3 script that creates a Countdown timer based on the KeyCombination used which is then written to a text file used by StreamlabsOBS. The idea is that when a KeyCombo is pressed (e.g ctrl+alt+z) a function starts a timer, and at the same time, another function writes the current time in the countdown to a txt file. This script would ideally be running during the entire stream.
So far, I can get the countdown working and writing to the file exactly how I want it to. But it seems the Thread is still alive after finishing the countdown. I'm not sure if this is a problem or not. Another thing is that I want to implement some kind of pause feature, that would pause the timer function. I'm not sure how to even start on that part.
The print statements are for me to know what part of the function I am at.
from pynput import keyboard
from pathlib import Path
from threading import Thread
import queue
from time import sleep
script_location = Path(__file__).absolute().parent
timer_queue = queue.Queue()
def storeInQueue(function):
print("Sent Start Thread msg")
def storer(*args):
for time in function(*args):
timer_queue.put(time)
print(f"stored {time}")
return storer
#storeInQueue
def timer(t):
print("Iterating Timer Loop")
while t > -1:
yield t
sleep(1)
t -= 1
def speakKorean():
print("starting Thread")
timer_thread = Thread(target=timer, args=(5,))
timer_thread.start()
ctime = timer_queue.get()
while ctime >-1:
with open(script_location / 'ChronoDown.txt', "w") as timer_file:
timer_file.write(f"Speak Korean for {ctime}s")
timer_file.flush()
sleep(1)
ctime = timer_queue.get()
if ctime == 0: break
print('Speak Korean done!')
with open(script_location / 'ChronoDown.txt', "w") as timer_file:
timer_file.write(f"Done!")
timer_file.flush()
while timer_thread.is_alive:
print("timer thread still running?")
timer_thread.join()
break
if timer_thread.is_alive:
print("didn't work")
def on_activate_z():
timer_file = open(script_location / 'ChronoDown.txt', "w")
timer_file.write("other keywords")
timer_file.close()
def on_activate_c():
korean_thread = Thread(target=speakKorean,)
korean_thread.start()
print("Working")
def on_activate_x():
timer_file = open(script_location / 'ChronoDown.txt', "w")
timer_file.write("No cursing for time")
timer_file.close()
with keyboard.GlobalHotKeys({
'<ctrl>+<alt>+z': on_activate_z,'<ctrl>+<alt>+c': on_activate_c,
'<ctrl>+<alt>+x': on_activate_x}) as h:
h.join()
My console output looks like this after I run it. I'm not sure why "Sent Start Thread msg" sends before I start thread too.
Sent Start Thread msg
starting Thread
Working
Iterating Timer Loop
stored 5
stored 4
stored 3
stored 2
stored 1
stored 0
Speak Korean done!
timer thread still running?
didn't work
Also if you have any optimization tips that would be appreciated. Thank you in advance for any help.
Thanks to #furas , I've now implemented a pause function that properly resumes as well. This is my updated code :
from pynput import keyboard
from pathlib import Path
from threading import Thread
import queue
from time import sleep
script_location = Path(__file__).absolute().parent
timer_queue = queue.Queue()
paused = False
while paused == False:
def storeInQueue(function):
print("Sent Start Thread msg")
def storer(*args):
for time in function(*args):
timer_queue.put(time)
print(f"stored {time}")
return storer
#storeInQueue
def timer(t):
print("Iterating Timer Loop")
while t > -1:
if paused == False:
yield t
sleep(1)
t -= 1
else: continue
def speakKorean():
print("starting Thread")
timer_thread = Thread(target=timer, args=(5,))
timer_thread.start()
ctime = timer_queue.get()
while ctime >-1:
with open(script_location / 'ChronoDown.txt', "w") as timer_file:
timer_file.write(f"Speak Korean for {ctime}s")
timer_file.flush()
sleep(1)
ctime = timer_queue.get()
if ctime == 0: break
print('Speak Korean done!')
with open(script_location / 'ChronoDown.txt', "w") as timer_file:
timer_file.write(f"Done!")
timer_file.flush()
timer_thread.join()
if timer_thread.is_alive():
print("didn't work")
else: print("its dead")
def on_activate_z():
global paused
timer_file = open(script_location / 'ChronoDown.txt', "w")
timer_file.write("Paused")
timer_file.close()
if paused == True:
paused = False
print(f'Paused = {paused}')
else:
paused =True
print(f'Paused = {paused}')
def on_activate_c():
korean_thread = Thread(target=speakKorean,)
korean_thread.start()
print("Working")
def on_activate_x():
timer_file = open(script_location / 'ChronoDown.txt', "w")
timer_file.write("No cursing for time")
timer_file.close()
with keyboard.GlobalHotKeys({
'<ctrl>+<alt>+z': on_activate_z,'<ctrl>+<alt>+c': on_activate_c,
'<ctrl>+<alt>+x': on_activate_x}) as h:
h.join()
The main differences:
My entire code is now encapsulated in a While paused == False loop, which allows me to pause my timer function based on the state of paused using an if statement
I've added the missing ( ) to timer_thread.is_alive() which allowed me to properly end the timer Thread
I want to detect a key pressed in python without using "with", because I want it to show a text in a while
all this with the pynput library:
import time
from pynput import keyboard
i = 0
while True:
if event.key == keyboard.Key.esc:
break
else:
if a == "hello":
print("y")
else:
print("n")
if i % 2 = 0:
a = "hello"
else
a = "good bye"
i += 1
print(a)
time.sleep(2)
pynput's Events blocks by default. You can .get to limit how long it blocks for:
from pynput import keyboard
import time
i = 0
a = "start"
while True:
if a == "hello":
print("y")
else:
print("n")
if i % 2 == 0:
a = "hello"
else:
a = "good bye"
i += 1
print(a)
# Not needed anymore, we're going to block waiting for key events for 2 seconds
# time.sleep(2)
with keyboard.Events() as events:
# Block at most for two seconds
event = events.get(2.0)
if event is not None:
if event.key == keyboard.Key.esc:
break
This won't necessarily always block for two seconds if the user presses some other key. You can either add code to check for that condition and keep calling events.get till enough time has passed, or use keyboard.Listener to react to events in real time.
I am writing a program in Python to run on a Raspberry Pi in order to control my Wurlitzer jukebox. The program current accepts the codes for "record selection" (A1, B1, C4, etc.), add those codes to a playlist, and executes the list. My issue is that once a song starts, I would like to be able to press a button ("Y" in the current code) to skip the currently playing song. I can't get this to work.
If I use "player.next()" I get an error: 'MediaPlayer' object has no attribute 'next'.
I tried to stop the player and restart it (thinking it would pick up the next song in the Playlist. This doesn't even stop the player.
I do not want to use subprocess if I can avoid it. I'd like to figure out a way within Python to do the skipping. How would one accomplish this?
import os, sys, csv, vlc, time, threading
from pynput.keyboard import Key, Listener
DefaultUSBPath="/media/pi"
PlayHistory="PlayHistory.csv"
#
# Declare variables
#
USBDrive = None
Action = None
Playlist = []
SelectionCount = []
Sel_char = None
#
# Find the USB Drive
#
for item in os.listdir(DefaultUSBPath):
if os.path.isdir(os.path.join(DefaultUSBPath, item)):
if USBDrive is None:
USBDrive = os.path.join(DefaultUSBPath, item)
else:
USBDrive = USBDrive + ";" + os.path.join(DefaultUSBPath, item)
if USBDrive is None:
print ("Error(0) - No USB Drive detected")
sys.exit()
elif ";" in USBDrive:
print ("Error(1) - More than one USB Drive detected.")
sys.exit()
#
# Adding to playlist - Returns directory contents and adds to playlist
#
def addplaylist(track):
list = None
if os.path.isdir(os.path.join(USBDrive, track)):
files = [f for f in os.listdir(os.path.join(USBDrive, track)) if os.path.isfile(os.path.join(USBDrive, track, f))]
for f in files:
if list is None:
list = os.path.join(USBDrive, track, f)
else:
list = list + ";" + os.path.join(USBDrive, track, f)
else:
print ("Error(2) - Selection is invalid")
if list is not None:
if ";" in list:
list = list.split(";")
else:
print ("Error(3) - Selection has no media")
return list
#
# MediaPlayer function
#
def MusicPlayer(P):
global Playlist, player
while len(Playlist) > 0:
song=Playlist.pop(0)
print("Song: ")
print(song)
player=vlc.MediaPlayer(song)
player.play()
#
# Define keyboard actions
#
def on_press(key):
global Action, Playlist, player
try:
Sel_char = int(key.char)
except:
try:
Sel_char = str(key.char)
Sel_char = Sel_char.upper()
except:
Sel_char = None
if Sel_char == "Z":
return False
elif Sel_char == "Y":
print("Skip")
#player.next() This line causes 'MediaPlayer' object has no attribute 'next'
time.sleep(1)
MusicPlayer(Playlist)
elif type(Sel_char) == str:
Action = Sel_char
elif type(Sel_char) == int:
Action = Action + str(Sel_char)
print("Action: " + Action)
Plist = addplaylist(Action)
if Plist is not None:
print("Added to playlist")
Playlist.append(Plist)
print(Plist)
MusicPlayer(Playlist)
else:
pass
#
# Read keyboard input
#
with Listener(on_press=on_press) as listener:
listener.join()
print ("")
print ("Have a nice day!")
print ("")
sys.exit()
The way you have it coded, I expect you'd have to stop it, remove the current media from the list, then re-start it.
However you may be better off running with a media_list_player, see below for a bare bones version. Note, I'm on Linux and had to hack some code to get the key input, rather than using a specific library or spend time on it, but it should give you enough to work with.
Edit
I apologise, there is a much simpler method when using a media_list_player, although if you want finer control you should use the media_list_player where you control the list's index or for full control use a media_player_new() but that's beyond the scope of this question. (I'll leave the original answer below this code, as it may be useful)
import vlc
import time
## pinched from vlc for keyboard input
import termios
import tty
import sys
mymedia = ["vp.mp3","vp1.mp3","happy.mp3","V1.mp4"]
def getch(): # getchar(), getc(stdin) #PYCHOK flake
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
return ch
## end pinched code
def jukebox():
player.play_item_at_index(0)
while True:
time.sleep(0.25)
k = getch()
if k == "n": #Next
player.next()
if k == "p": #Previous
player.previous()
if k == " ": #Pause
player.pause()
if k == "q": #Quit
player.stop()
return True
player.next()
vlc_instance = vlc.Instance('--no-xlib --quiet ') # no-xlib for linux and quiet don't complain
player = vlc_instance.media_list_player_new()
Media = vlc_instance.media_list_new(mymedia)
player.set_media_list(Media)
print("Welcome to Jukebox")
print("Options - space = Play/Pause, n = Next, p = Previous, q = Quit")
print("Media",mymedia)
jukebox()
Original code
import vlc
import time
## pinched from vlc for keyboard input
import termios
import tty
import sys
def getch(): # getchar(), getc(stdin) #PYCHOK flake
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
return ch
## end pinched code
vlc_instance = vlc.Instance()
player = vlc_instance.media_list_player_new()
mymedia = ["vp.mp3","vp1.mp3","happy.mp3"]
Media = vlc_instance.media_list_new(mymedia)
player.set_media_list(Media)
for index, name in enumerate(mymedia):
print("Playing:",name)
player.play_item_at_index(index)
time.sleep(1)
while player.get_state() != 6:
time.sleep(1)
k = getch()
if k == "y":
player.stop()
break
Everyone, hello!
I'm currently using trying to communicate with my Arduino (whom is hooked up my Raspberry Pi through Serial) and using the information in my Python script on my Raspberry Pi.
That said, my Python script has to wait for the Arduino to report back it's data before I want the script to continue, although, I'm not entirely sure on how to do that.
This is what I've got so far:
#!/usr/bin/env python
import time
import serial
import RPi.GPIO as GPIO
ser = serial.Serial('/dev/ttyACM0', 9600)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(20, GPIO.OUT) #green LED
GPIO.setup(16, GPIO.IN, GPIO.PUD_UP) #green button
GPIO.output(20, True) #green ON
start = time.time()
while True:
if (GPIO.input(16) == False):
print "green button pressed"
time.sleep(0.25)
start = time.time()
while (GPIO.input(16) == False):
time.sleep(0.01)
if (GPIO.input(16) == True):
print "released!"
end = time.time()
elapsed = end - start
print elapsed
if elapsed >= 5:
print "longer than 5s"
else:
print "shorter than 5s"
ser.write("0")
while True:
print ser.readline().rstrip()
if ser.readline().rstrip() == "a":
print "ready"
continue
if ser.readline().rstrip() == "b":
print "timeout"
break
if ser.readline().rstrip()[0] == "c":
print "validated: " + ser.readline().rstrip()[2]
break
As you can see, I'm sending the number 0 to my Arduino, and wait for it to respond with a, which means it's ready. After which, when it has the data, it sends out the message "c", as a result, I need to wait for 2 different seperate messages.
I've tried to do this by having a loop and breaking it when I have what I need, but this doesn't work.
It currently does go into the loop, and it prints out the "a" message, but doesn't come back with the second message.
Any idea how to properly tie this loop?
Thank you!
use functions
def wait_for(ser,targetChar):
resp = ""
while True:
tmp=ser.read(1)
resp = resp + tmp
if not tmp or tmp == targetChar:
return resp
first_resp = wait_for(ser,'a')
second_resp = wait_for(ser,'c')
while not second_resp.endswith('c'):
print "RETRY"
second_resp = wait_for(ser,'c')
This worked out well for me to keep my while, and escape the block until I get what i want:
loop = 1
while loop == 1:
message = ser.readline().rstrip()
if message == "a":
print "ready"
continue
if message == "b":
print "Timeout"
loop = 0
if message[0] == "c":
print "Validated: " + message[2]
loop = 0
if message == "d":
print "error, try again"
loop = 0
I'm new to Python and have been googling for a couple of days and read all I can find on this forum. Might be that I don't understand it all but I haven't found a solution to my problem yet. Ask for forgiveness already if there's an answer already to my problem, then I haven't understood it.
I want to make a Pause function for my program Tennismatch. The program will when it's being run print the score of a tennis match like this: "15-0, 15-15 etc ongoing till the match ends. It will print the score line by line.
I want the user to be able to pause after x number of balls, games, etc. So I don't know when the user wants to pause and after the user has paused I want the user to be able to resume the tennismatch where it was.
Have seen the time.sleep() but as I have understood it you must know when you want to pause to use this and it also ain't an indefinetie pause like I want. With input() it's the same.
Am going to make a GUI later on when the code is finished. Happy for anything that leads me to solving my problem.
I use Windows and Python 3.42 and run the program in Shell.
A piece of the code (haven't written it all yet, it's more of a general situation when something is being printed line after line for some time and want to be able do pause in the CIL:
#self.__points = [0,0]
def playGame(self):
if self.server == True: #self.server is either True or False when someone calls playGame()
server = self.player_1.get_win_serve() #self.player_1 = an object of a class Player():
else:
server = self.player_2.get_win_serve() #get_win_serve() method returns the probability to win his serv (1-0)
while (0 < self.__points[0] - self.__points[1] >= 2 or 0 < self.__points[1] - self.__points[0] >= 2) and (self.__points[1] >= 4 or self.__points[0] >= 4):
x = random.uniform(0,1)
if x > 0 and x < server:
self.__points[0] += 1
else:
self.__points[1] += 1
# print('The score, by calling a score() function that I haven't written yet')
For dealing with events in main loop you need to make a separated thread which capture input or any other event.
import sys
from sys import stdin
from time import sleep
from threading import Thread
from Queue import Queue, Empty
def do_something():
sleep(1)
print 42
def enqueue_output(queue):
while True:
# reading line from stdin and pushing to shared queue
input = stdin.readline()
print "got input ", input
queue.put(input)
queue = Queue()
t = Thread(target=enqueue_output, args=(queue,))
t.daemon = True
t.start()
pause = False
try:
while True:
try:
command = queue.get_nowait().strip()
print 'got from queue ', command
except Empty:
print "queue is empty"
command = None
if command:
if command == 'p':
pause = True
if command == 'u':
pause = False
if not pause:
print pause
do_something()
except KeyboardInterrupt:
sys.exit(0)
I came up with the following.
while True:
try:
## Keep doing something here
## your regular code
print '.',
except KeyboardInterrupt:
## write or call pause function which could be time.sleep()
print '\nPausing... (Hit ENTER to continue, type quit to exit.)'
try:
response = raw_input()
if response.lower() == 'quit':
break
print 'Quitting...'
except KeyboardInterrupt:
print 'Resuming...'
continue
The Event loop might as well be the code I wrote with.
I don't see any user input so I assume that x emulates it. To pause the game if x < 0.1 and to unpause(/resume) it if x > 0.9, you could:
while your_condition(self.__points):
x = random.random()
if x < 0.1: # pause
self.pause()
elif x > 0.9: # resume
self.resume()
if self.is_paused:
continue # do nothing else only wait for input (`x`)
# assume your_condition() has no side-effects
# here's what the resumed version does:
print("...")
# change self.__points, etc
where pause(), resume(), is_paused() methods could be implemented as:
def __init__(self):
self.is_paused = False
def pause(self):
self.is_paused = True
def resume(self):
self.is_paused = False
as you can see the implementation is very simple.