Add acoustic_recorder/src/acoustic_recorder/core.py
This commit is contained in:
commit
52650af099
1 changed files with 56 additions and 0 deletions
56
acoustic_recorder/src/acoustic_recorder/core.py
Normal file
56
acoustic_recorder/src/acoustic_recorder/core.py
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import os
|
||||
import wave
|
||||
import datetime
|
||||
from pathlib import Path
|
||||
from typing import Union
|
||||
|
||||
import numpy as np
|
||||
import sounddevice as sd
|
||||
|
||||
|
||||
class AudioRecordingError(Exception):
|
||||
"""Fehler bei der Aufnahme oder Speicherung von Audiodaten."""
|
||||
|
||||
|
||||
def record_audio(duration: int) -> str:
|
||||
"""Zeichnet Audio vom Standardmikrofon für die angegebene Dauer auf und speichert es als WAV-Datei.
|
||||
|
||||
Args:
|
||||
duration (int): Aufnahmedauer in Sekunden.
|
||||
|
||||
Returns:
|
||||
str: Pfad zur gespeicherten WAV-Datei.
|
||||
|
||||
Raises:
|
||||
AudioRecordingError: Wenn ein Fehler bei der Aufnahme oder Speicherung auftritt.
|
||||
ValueError: Wenn die Eingabe ungültig ist (z. B. negative Dauer).
|
||||
"""
|
||||
if not isinstance(duration, int) or duration <= 0:
|
||||
raise ValueError("'duration' muss eine positive ganze Zahl sein.")
|
||||
|
||||
samplerate = 44100 # Hz
|
||||
channels = 2 # Stereo
|
||||
|
||||
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
output_dir = Path("output")
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
filepath = output_dir / f"recording_{timestamp}.wav"
|
||||
|
||||
try:
|
||||
# Aufnahme starten
|
||||
print(f"Starte Aufnahme für {duration} Sekunden ...")
|
||||
recording = sd.rec(int(duration * samplerate), samplerate=samplerate, channels=channels, dtype='int16')
|
||||
sd.wait()
|
||||
|
||||
# In WAV speichern
|
||||
with wave.open(str(filepath), 'wb') as wf:
|
||||
wf.setnchannels(channels)
|
||||
wf.setsampwidth(2) # 16-bit = 2 Bytes
|
||||
wf.setframerate(samplerate)
|
||||
wf.writeframes(recording.tobytes())
|
||||
|
||||
print(f"Aufnahme abgeschlossen: {filepath}")
|
||||
return str(filepath)
|
||||
|
||||
except Exception as e:
|
||||
raise AudioRecordingError(f"Fehler bei der Audioaufnahme: {e}") from e
|
||||
Loading…
Reference in a new issue