-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
82 lines (64 loc) · 2.11 KB
/
main.py
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import importlib.util
import subprocess
import os
from datetime import datetime
import time
if importlib.util.find_spec("pyaudio") is None:
print("pyaudio is not installed. Installing...")
subprocess.run(["pip", "install", "pyaudio"])
if importlib.util.find_spec("wave") is None:
print("wave is not installed. Installing...")
subprocess.run(["pip", "install", "wave"])
import pyaudio
import wave
def spinner():
while True:
for cursor in '|/-\\':
yield cursor
spinner_handler = spinner()
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
CHUNK = 1024
try:
RECORD_MINUTES = int(input("enter the number of minutes to record: "))
except ValueError:
print("ERROR: input Please enter a valid integer.")
exit()
current_datetime = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
OUTPUT_FILENAME = f"./audios/audio_{current_datetime}.wav"
audio = pyaudio.PyAudio()
mic_device_index = None
for i in range(audio.get_device_count()):
info = audio.get_device_info_by_index(i)
if 'microphone' in info['name'].lower():
mic_device_index = i
break
if mic_device_index is None:
print("External microphone not found.")
exit()
stream = audio.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK,
input_device_index=mic_device_index)
print("Recording....", end='', flush=True)
frames = []
record_frames = int(RATE / CHUNK * 60 * RECORD_MINUTES)
for i in range(record_frames):
data = stream.read(CHUNK)
frames.append(data)
if i % 100 == 0:
print(f'\b{next(spinner_handler)}', end='', flush=True)
time.sleep(0.1)
print("\bFinished recording.")
stream.stop_stream()
stream.close()
audio.terminate()
with wave.open(OUTPUT_FILENAME, 'wb') as wf:
wf.setnchannels(CHANNELS)
wf.setsampwidth(audio.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
print(f"Audio saved to {OUTPUT_FILENAME}")