Du kannst die Module "pyaudio" für die Aufnahme und "pydub" für die Konvertierung nach MP3 verwenden.
import pyaudio
import wave
from pydub import AudioSegment
def record_audio(filename, duration):
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
frames = []
print("Recording...")
for _ in range(0, int(RATE / CHUNK * duration)):
data = stream.read(CHUNK)
frames.append(data)
print("Recording finished.")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(filename, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
def convert_to_mp3(input_file, output_file):
sound = AudioSegment.from_wav(input_file)
sound.export(output_file, format="mp3")
# Aufnahme starten und speichern
output_wav = "output.wav"
record_duration = 5 # Aufnahmezeit in Sekunden
record_audio(output_wav, record_duration)
# Konvertieren nach MP3
output_mp3 = "output.mp3"
convert_to_mp3(output_wav, output_mp3)