Re: [Tutor] call key on_press event multiple times when key is held down

2017-07-13 Thread Joel Goldstick
On Thu, Jul 13, 2017 at 3:36 AM, Carlton Banks  wrote:

> So i finally made it work..
> My error was caused in the callback function, which
> aborted the stream, hence didn’t record.
>
> This was the solution I ended with:
>
> https://pastebin.com/isW2brW2 
>
>
Carlton, please don't post above the discusion -- post below or interleave
where appropriate.  Also, paste your code in the message next time (which I
have done below)

>
> > Den 10. jul. 2017 kl. 11.10 skrev Alan Gauld via Tutor  >:
> >
> > On 04/07/17 13:45, Carlton Banks wrote:
> >
> >> Any suggestion on any GUI solutions?
> >
> > Here is a Tkinter solution that increments a counter
> > while the mouse button is pressed. It should give you the idea...
> > Obviously you need to replace the counter increment
> > with your desired processing. And the print statements
> > are just to show the events being processed.
> >
> > ##
> > import tkinter as tk
> >
> > display = "count: "
> > flag = False
> > counter = 0
> >
> > def do_down(e):
> >global flag
> >print('Key down')
> >flag = True
> >after_loop()
> >
> > def do_up(e):
> >global flag
> >print('key up')
> >flag = False
> >
> > def after_loop():
> >print('looping')
> >global counter
> >counter += 1
> >l['text'] = display +str(counter)
> >if flag:
> >   top.after(10,after_loop)
> >
> >
> > top = tk.Tk()
> > l = tk.Label(top,text=display+'0')
> > l.pack()
> > l.bind("",do_down)
> > l.bind("",do_up)
> > top.mainloop()
> >
> > ###
> >
> > HTH
> > --
> > Alan G
> > Author of the Learn to Program web site
> > http://www.alan-g.me.uk/
> > http://www.amazon.com/author/alan_gauld
> > Follow my photo-blog on Flickr at:
> > http://www.flickr.com/photos/alangauldphotos
> >
> >
> > ___
> > Tutor maillist  -  Tutor@python.org
> > To unsubscribe or change subscription options:
> > https://mail.python.org/mailman/listinfo/tutor
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

from pynput import keyboard
import time
import pyaudio
import wave
import math

CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
WAVE_OUTPUT_FILENAME = "output.wav"



class MyListener(keyboard.Listener):
def __init__(self):
super(MyListener, self).__init__(on_press=self.on_press,
on_release=self.on_release)
self.key_pressed = None


def on_press(self, key):
if key == keyboard.Key.cmd_l:
self.p = pyaudio.PyAudio()
self.frames = []

self.stream = self.p.open(format=FORMAT,
 channels=CHANNELS,
 rate=RATE,
 input=True,
 frames_per_buffer=CHUNK,
 stream_callback = self.callback)

print ("Stream active? " + str(self.stream.is_active()))
self.key_pressed = True

def on_release(self, key):
if key == keyboard.Key.cmd_l:
self.key_pressed = False

def callback(self,in_data, frame_count, time_info, status):
if self.key_pressed == True:
#stream_queue.put(in_data)
print("record")
self.frames.append(in_data)
return (in_data, pyaudio.paContinue)

elif self.key_pressed == False:
#stream_queue.put(in_data)
self.frames.append(in_data)
return (in_data, pyaudio.paComplete)

else:
return (in_data,pyaudio.paContinue)



class yesno_generator:
def __init__(self,pattern_length):
self.pattern_length = pattern_length
self.limit = math.pow(2,pattern_length)-1
self.step = 0
def begin(self):
if self.step =< self.limit:


def generate_patter(self):
pattern = bin(self.step)[2:].zfill(sef.length)




listener = MyListener()
listener.start()
started = False



while True:
time.sleep(0.1)
if listener.key_pressed == True and started == False:
started = True
listener.stream.start_stream()
print ("Start stream -  Key is down")

#   elif listener.key_pressed == True and started == True:
#print("stream has started and key is still down")
#print("Stream is active? " + str(listener.stream.is_active()))
#print("Stream is stopped? " + str(listener.stream.is_stopped()))
#print("Stream is time? " + str(listener.stream.get_time()))

elif listener.key_pressed == False and started == True:
print("Key has been released")
listener.stream.stop_stream()
listener.stream.close()
print("stream has been closed")
listener.p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setncha

Re: [Tutor] call key on_press event multiple times when key is held down

2017-07-13 Thread Carlton Banks
So i finally made it work.. 
My error was caused in the callback function, which
aborted the stream, hence didn’t record. 

This was the solution I ended with:

https://pastebin.com/isW2brW2 


> Den 10. jul. 2017 kl. 11.10 skrev Alan Gauld via Tutor :
> 
> On 04/07/17 13:45, Carlton Banks wrote:
> 
>> Any suggestion on any GUI solutions?
> 
> Here is a Tkinter solution that increments a counter
> while the mouse button is pressed. It should give you the idea...
> Obviously you need to replace the counter increment
> with your desired processing. And the print statements
> are just to show the events being processed.
> 
> ##
> import tkinter as tk
> 
> display = "count: "
> flag = False
> counter = 0
> 
> def do_down(e):
>global flag
>print('Key down')
>flag = True
>after_loop()
> 
> def do_up(e):
>global flag
>print('key up')
>flag = False
> 
> def after_loop():
>print('looping')
>global counter
>counter += 1
>l['text'] = display +str(counter)
>if flag:
>   top.after(10,after_loop)
> 
> 
> top = tk.Tk()
> l = tk.Label(top,text=display+'0')
> l.pack()
> l.bind("",do_down)
> l.bind("",do_up)
> top.mainloop()
> 
> ###
> 
> HTH
> -- 
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] call key on_press event multiple times when key is held down

2017-07-10 Thread Carlton Banks
Thanks for the response :)
> Den 10. jul. 2017 kl. 10.54 skrev Peter Otten <__pete...@web.de>:
> 
> Carlton Banks wrote:
> 
>> So i tried a different solution, introducing two threads one handling the
>> keyboard, and the other one is a while true, that keeps running.
>> 
>> https://pastebin.com/U0WVQMYP 
>> 
>> but for some reason, am I constantly running into IOerror, hence
>> no frames is being recorded.  Any suggestion on why?
> 
> Please remember to always provide the traceback.
> 
There is no traceback, no error message besides the IOerror caught by the 
try/execpt. 

>> while True:
>>time.sleep(0.1)
>>if listener.key_pressed == True and started == False:
>>started = True
>>listener.stream.start_stream()
>>print "start Stream"
>> 
>>elif listener.key_pressed == False and started == True:
>>print "Something coocked"
>>listener.stream.stop_stream()
> 
> Did you get a non-empty output.wav?

The output.wav is empty

>>listener.stream.close()
> 
> you see the IOError on the second attempt to record something.

I see the IOerror while i have the key down,  not only on the first or second 
attempt..

>>p.terminate()

> As you are only prepared to record once and another record would overwrite 
> the file anyway (at least that's what I suppose
> 

currently I am trying to make one recording work like this,
but would like to have the functionality of keep generating different audio 
files,
with different utterances..
>>wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
> 
> to do) perhaps you can omit the while-True loop altogether. Or you omit the 
> stream.close() call until after that loop (though there seems to be no way 
> to exit it cleanly at the moment).
> 
Not sure if that is the problem here… 
> Note that these are just ideas, I'm not familiar with pyaudio, or pynput, or 
> wave.
> 
And thanks for suggestioning them :)
>>wf.setnchannels(CHANNELS)
>>wf.setsampwidth(p.get_sample_size(FORMAT))
>>wf.setframerate(RATE)
>>wf.writeframes(b''.join(frames))
>>wf.close()
>> 
>>started = False
>> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] call key on_press event multiple times when key is held down

2017-07-10 Thread Peter Otten
Carlton Banks wrote:

> So i tried a different solution, introducing two threads one handling the
> keyboard, and the other one is a while true, that keeps running.
> 
> https://pastebin.com/U0WVQMYP 
> 
> but for some reason, am I constantly running into IOerror, hence
> no frames is being recorded.  Any suggestion on why?

Please remember to always provide the traceback.

> while True:
> time.sleep(0.1)
> if listener.key_pressed == True and started == False:
> started = True
> listener.stream.start_stream()
> print "start Stream"
> 
> elif listener.key_pressed == False and started == True:
> print "Something coocked"
> listener.stream.stop_stream()

Did you get a non-empty output.wav?

If yes, my guess is that you can record something the first time you press 
the key, and when you release it and close the audio input with

> listener.stream.close()

you see the IOError on the second attempt to record something.

> p.terminate()


As you are only prepared to record once and another record would overwrite 
the file anyway (at least that's what I suppose
 
> wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')

to do) perhaps you can omit the while-True loop altogether. Or you omit the 
stream.close() call until after that loop (though there seems to be no way 
to exit it cleanly at the moment).

Note that these are just ideas, I'm not familiar with pyaudio, or pynput, or 
wave.

> wf.setnchannels(CHANNELS)
> wf.setsampwidth(p.get_sample_size(FORMAT))
> wf.setframerate(RATE)
> wf.writeframes(b''.join(frames))
> wf.close()
> 
> started = False
> 




___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] call key on_press event multiple times when key is held down

2017-07-10 Thread Carlton Banks
So i tried a different solution, introducing two threads one handling the 
keyboard, 
and the other one is a while true, that keeps running. 

https://pastebin.com/U0WVQMYP 

but for some reason, am I constantly running into IOerror, hence 
no frames is being recorded.  Any suggestion on why?
> Den 4. jul. 2017 kl. 14.45 skrev Carlton Banks :
> 
>> 
>>> Interesting solution, but still find a bit "dirty hackish”
>>> to involve a timer in this..  I guess it just would be neat if 
>>> it just worked as i thought it to be.  But i guess i have to look into 
>>> curses.
>> 
>> A timer based loop is actually the standard pattern for
>> implementing a loop in an event driven environment (the
>> main alternative is to launch a background thread).
>> It's how most GUIs handle such scenarios.
>> 
>> The problem in a CLI solution is that you have to build your
>> own timer event system (usually based on time.sleep() or
>> similar). Hence the suggestion to use a GUI.
>> 
> 
> Any suggestion on any GUI solutions?
> 
> 
> Regards 
> Carl
> 

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] call key on_press event multiple times when key is held down

2017-07-04 Thread eryk sun
On Tue, Jul 4, 2017 at 8:50 AM, Carlton Banks  wrote:
> I am using pynput  for keyboard events

You could use an event that enables a recording loop. The on_press and
on_release callbacks of the Listener [1] would set() and clear() this
event, respectively. For example:

import threading
from pynput import keyboard

def main():
do_record = threading.Event()

def on_press(key):
if key == keyboard.Key.cmd_l:
do_record.set()

def on_release(key):
if key == keyboard.Key.cmd_l:
do_record.clear()

with keyboard.Listener(on_press=on_press,
   on_release=on_release) as listener:

do_record.wait()

frames = []

while do_record.is_set():
print('Started recording')
# record and append audio frame

print('Stopped recording')
listener.join()

[1]: http://pythonhosted.org/pynput/keyboard.html#pynput.keyboard.Listener
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] call key on_press event multiple times when key is held down

2017-07-04 Thread Alan Gauld via Tutor
On 04/07/17 09:50, Carlton Banks wrote:
> I am trying to record from my microphone while i press down a button,

First question is which OS?
That makes a big difference in this kind of scenario.

> the library I am using is not able to detect on hold event. 

There isn't really any concept of a hold event, you usually
have to detect repeated press events. However I don;t know
the library you are using, I normally just use the standard
library for such things, or build a simple GUI...

> It only detect on press, which happens once, 

That's unusual, usually you get a repeated stream of
press events when you hold a key down. But it does
depend on the OS and environment. Your library may
indeed just be detecting the initial key down and
be waiting for the key up event.

> So does any of you know any libraries that monitor> state of the keyboard,

There are several but it depends on your OS.
In the standard library
Unix variants can use curses.
Windows users have msvcrt.

And there are several 3rd party libraries that try
to do in a platform independent way - I'm guessing
the one you are using is one such.

Another way to tackle it is to switch your code so
it works with a toggle. Set the toggle to on in
the on_press handler. Set it to off in the
on_release handler

Then trigger a timer loop that runs for as long
as the toggle is set. This is probably easiest
done within a GUI.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] call key on_press event multiple times when key is held down

2017-07-04 Thread Carlton Banks
I am trying to record from my microphone while i press down a button, problem 
is that the library I am using is not able to detect on hold event. It only 
detect on press, which happens once, which means that the microphone only 
records one sample..

import pyaudio
import wave
from pynput import keyboard

CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK) 
frames = []

def on_press(key):
if key == keyboard.Key.cmd_l:
print('- Started recording -'.format(key))
try:
data = stream.read(CHUNK)
frames.append(data)
except IOError: 
print 'warning: dropped frame' # can replace with 'pass' if no 
message desired 
else:
print('incorrect character {0}, press cmd_l'.format(key))


def on_release(key):
print('{0} released'.format(
key))
if key == keyboard.Key.cmd_l:
print('{0} stop'.format(key))
keyboard.Listener.stop
return False

print("* recording")


with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()

print("* done recording")

stream.stop_stream()
stream.close()
p.terminate()

wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
I am using pynput  for keyboard events and 
pyaudio for recording. I am pretty sure that this should be the error, as the 
example script for recording, picks up samples in a for loop, which works. 

So does any of you know any libraries that monitors state of the keyboard, or 
any ideas on how to get this working?.. I tried with a while look inside the 
on_press callback but that resulted in me getting stuck that callback.


How can i fix this?


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor