commit | author | age
|
341356
|
1 |
import pyaudio |
CW |
2 |
import wave |
|
3 |
|
|
4 |
# Initialize PyAudio |
|
5 |
p = pyaudio.PyAudio() |
|
6 |
|
|
7 |
# List available input devices |
|
8 |
print("Available audio input devices:") |
|
9 |
for i in range(p.get_device_count()): |
|
10 |
device_info = p.get_device_info_by_index(i) |
|
11 |
if device_info['maxInputChannels'] > 0: |
|
12 |
print(f"Device ID {i}: {device_info['name']} (Max channels: {device_info['maxInputChannels']})") |
|
13 |
|
|
14 |
# Prompt user to select a device |
|
15 |
device_index = int(input("Please select the device ID to use for recording: ")) |
|
16 |
|
|
17 |
# Parameters |
|
18 |
CHANNELS = 19 |
|
19 |
SAMPLE_RATE = 48000 |
|
20 |
CHUNK = 2048 # Number of frames per buffer |
|
21 |
FORMAT = pyaudio.paInt24 # 16-bit audio |
|
22 |
RECORD_SECONDS = 10 # Duration to record (in seconds) |
|
23 |
OUTPUT_FILENAME = "output.wav" |
|
24 |
|
|
25 |
# Get the chosen device's info tso validate it can support 19 channels and 48kHz |
|
26 |
device_info = p.get_device_info_by_index(device_index) |
|
27 |
max_channels = device_info['maxInputChannels'] |
|
28 |
if max_channels < CHANNELS: |
|
29 |
print(f"Error: The selected device only supports {max_channels} channels, but 19 channels are required.") |
|
30 |
p.terminate() |
|
31 |
exit(1) |
|
32 |
|
|
33 |
# Open stream |
|
34 |
stream = p.open(format=FORMAT, |
|
35 |
channels=CHANNELS, |
|
36 |
rate=SAMPLE_RATE, |
|
37 |
input=True, |
|
38 |
input_device_index=device_index, |
|
39 |
frames_per_buffer=CHUNK) |
|
40 |
|
|
41 |
print(f"Recording {RECORD_SECONDS} seconds of audio from device ID {device_index}...") |
|
42 |
|
|
43 |
frames = [] |
|
44 |
|
|
45 |
print (f"Check status {stream.is_active()}") |
|
46 |
|
|
47 |
for _ in range(int(SAMPLE_RATE / CHUNK * RECORD_SECONDS)): |
|
48 |
|
|
49 |
try: |
|
50 |
# Record audio |
|
51 |
data = stream.read(CHUNK) |
|
52 |
frames.append(data) |
|
53 |
except: |
|
54 |
print ("Error") |
|
55 |
|
|
56 |
|
|
57 |
print("Finished recording.") |
|
58 |
|
|
59 |
|
|
60 |
print (f"Check status {stream.is_active()}") |
|
61 |
# Stop and close the stream |
|
62 |
stream.stop_stream() |
|
63 |
stream.close() |
|
64 |
|
|
65 |
# Terminate PyAudio |
|
66 |
p.terminate() |
|
67 |
|
|
68 |
# Save the recorded audio to a file |
|
69 |
wf = wave.open(OUTPUT_FILENAME, 'wb') |
|
70 |
wf.setnchannels(CHANNELS) |
|
71 |
wf.setsampwidth(p.get_sample_size(FORMAT)) |
|
72 |
wf.setframerate(SAMPLE_RATE) |
|
73 |
wf.writeframes(b''.join(frames)) |
|
74 |
wf.close() |
|
75 |
|
|
76 |
print(f"Audio saved to {OUTPUT_FILENAME}.") |
|
77 |
|