Created
November 15, 2024 22:47
-
-
Save KoStard/9ea143f0b0572044629800434b5a2453 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sounddevice as sd | |
import soundfile as sf | |
import numpy as np | |
import pydub | |
def record_audio(filename="recording.mp3", samplerate=44100): | |
# Initialize recording flag | |
recording = True | |
# Create array to store audio data | |
audio_data = [] | |
# Define callback function for the stream | |
def callback(indata, frames, time, status): | |
if status: | |
print(status) | |
if recording: | |
audio_data.append(indata.copy()) | |
# Create input stream | |
stream = sd.InputStream(callback=callback, channels=1, samplerate=samplerate) | |
print("Recording... Press Enter to stop.") | |
# Start recording | |
with stream: | |
# Wait for Enter key | |
input() | |
recording = False | |
# Convert recorded data to numpy array | |
audio_array = np.concatenate(audio_data, axis=0) | |
# Save as WAV first (temporary file) | |
temp_wav = "temp_recording.wav" | |
sf.write(temp_wav, audio_array, samplerate) | |
# Convert WAV to MP3 | |
audio = pydub.AudioSegment.from_wav(temp_wav) | |
audio.export(filename, format="mp3") | |
# Clean up temporary WAV file | |
import os | |
os.remove(temp_wav) | |
print(f"Recording saved as {filename}") | |
if __name__ == "__main__": | |
record_audio() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment