-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecord_audio_3.py
More file actions
61 lines (46 loc) · 1.64 KB
/
record_audio_3.py
File metadata and controls
61 lines (46 loc) · 1.64 KB
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
import sounddevice as sd
import soundfile as sf
import numpy as np
import time
from datetime import datetime
# datetime object containing current date and time
now = datetime.now()
dt_string = now.strftime("%d_%m_%Y_%H_%M_%S")
# Set the audio settings
SAMPLE_RATE = 16000
OUTPUT_FILE = "recorded_audio.wav"
# Initialize an empty list to store the recorded audio frames
audio_frames = []
# Function to check the recording flag from the shared file
def check_recording_flag():
try:
with open("recording_flag.txt", "r") as flag_file:
flag_value = flag_file.read().strip()
return flag_value == "1"
except FileNotFoundError:
return False
# Define the callback function that will be called for each audio block
def audio_callback(indata, frames, time, status):
if check_recording_flag():
audio_frames.append(indata.copy())
# Start the audio stream
stream = sd.InputStream(callback=audio_callback, channels=1, samplerate=SAMPLE_RATE)
stream.start()
# Wait for a short duration to avoid buffered noise
time.sleep(1)
# Record audio while the recording flag is set
while check_recording_flag():
time.sleep(0.1)
# Stop the audio stream
stream.stop()
stream.close()
# Check if any audio frames were recorded
if len(audio_frames) > 0:
# Concatenate the recorded audio frames into a single array
audio_data = np.vstack(audio_frames)
# Save the recorded audio to a WAV file
# sf.write(f'{now.strftime("%d_%m_%Y_%H_%M_%S")}_recorded_audio.wav', audio_data, SAMPLE_RATE)
sf.write(OUTPUT_FILE, audio_data, SAMPLE_RATE)
print("Audio saved to:", OUTPUT_FILE)
else:
print("No audio recorded.")