File size: 1,344 Bytes
9690d29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import pyaudio
from pynput import keyboard
import wave

# Define constants for PyAudio
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100

# Define the on_press function
def on_press(key):
    print("Key pressed: ", key)
    if key == keyboard.Key.esc:
        return False
    print(type(key))
    print(str(key))
    if str(key) == 'a':
        print('here')
        audio = pyaudio.PyAudio()
        stream = audio.open(format=FORMAT, channels=CHANNELS,
                            rate=RATE, input=True,
                            frames_per_buffer=CHUNK)
        print("Recording audio...")
        frames = []
        while True:
            data = stream.read(CHUNK)
            frames.append(data)
            if not keyboard.is_pressed('a'):
                break
            if not listener.running:
                break
        stream.stop_stream()
        stream.close()
        audio.terminate()
        print("Finished recording audio.")
        # Save recorded audio data to a .wav file
        wf = wave.open("recorded_audio.wav", 'wb')
        wf.setnchannels(CHANNELS)
        wf.setsampwidth(audio.get_sample_size(FORMAT))
        wf.setframerate(RATE)
        wf.writeframes(b''.join(frames))
        wf.close()

# Start the listener
with keyboard.Listener(on_press=on_press) as listener:
    listener.join()