Skip to content

Instantly share code, notes, and snippets.

@ducnh1022
Created February 24, 2026 06:45
Show Gist options
  • Select an option

  • Save ducnh1022/72585412f4b3dd06da5a895da2add58d to your computer and use it in GitHub Desktop.

Select an option

Save ducnh1022/72585412f4b3dd06da5a895da2add58d to your computer and use it in GitHub Desktop.
import sounddevice as sd
import soundfile as sf
import numpy as np
import queue
import datetime
import os
# ==============================
# CONFIG
# ==============================
SAMPLE_RATE = 16000
CHANNELS = 1
FILE_DURATION_MINUTES = 5 # mỗi file 5 phút
OUTPUT_FOLDER = "recordings"
os.makedirs(OUTPUT_FOLDER, exist_ok=True)
audio_queue = queue.Queue()
def audio_callback(indata, frames, time, status):
if status:
print(status)
audio_queue.put(indata.copy())
def generate_filename():
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
return os.path.join(OUTPUT_FOLDER, f"record_{timestamp}.wav")
def record_continuous():
print("🎙️ Recording started... Press Ctrl+C to stop.")
file_start_time = datetime.datetime.now()
filename = generate_filename()
file = sf.SoundFile(
filename,
mode='w',
samplerate=SAMPLE_RATE,
channels=CHANNELS
)
with sd.InputStream(
samplerate=SAMPLE_RATE,
channels=CHANNELS,
callback=audio_callback
):
while True:
data = audio_queue.get()
file.write(data)
# kiểm tra thời gian để chia file
elapsed = (datetime.datetime.now() - file_start_time).total_seconds()
if elapsed >= FILE_DURATION_MINUTES * 60:
file.close()
print(f"💾 Saved: {filename}")
file_start_time = datetime.datetime.now()
filename = generate_filename()
file = sf.SoundFile(
filename,
mode='w',
samplerate=SAMPLE_RATE,
channels=CHANNELS
)
if __name__ == "__main__":
try:
record_continuous()
except KeyboardInterrupt:
print("\n🛑 Recording stopped.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment