Spaces:
Sleeping
Sleeping
| import numpy as np | |
| import soundfile as sf | |
| import os | |
| import uuid | |
| def generate_audio_loop(style, bpm): | |
| # Ensure directory exists | |
| outdir = "assets/generated_beats" | |
| os.makedirs(outdir, exist_ok=True) | |
| # Audio settings | |
| sr = 44100 | |
| sec = 5 # shorter = safer for HF | |
| samples = int(sr * sec) | |
| t = np.linspace(0, sec, samples) | |
| # Pick a frequency based on style | |
| if style == "Country Rap": | |
| freq = 80 + bpm * 0.5 | |
| elif style == "Trap": | |
| freq = 120 + bpm * 0.3 | |
| elif style == "Dark Outlaw": | |
| freq = 60 + bpm * 0.4 | |
| elif style == "Drill": | |
| freq = 150 + bpm * 0.2 | |
| else: | |
| freq = 100 + bpm * 0.2 | |
| # Main tone | |
| waveform = 0.3 * np.sin(2 * np.pi * freq * t) | |
| # Add simple hi-hat clicks | |
| for i in range(0, samples, int(sr * 0.2)): | |
| if i < samples: | |
| waveform[i:i+200] += 0.5 * np.random.uniform(-1, 1, 200) | |
| # Normalize to float32 | |
| waveform = waveform.astype(np.float32) | |
| # Output file path | |
| filename = f"{uuid.uuid4().hex}.wav" | |
| output_path = os.path.join(outdir, filename) | |
| # Write audio | |
| try: | |
| sf.write(output_path, waveform, sr) | |
| except Exception as e: | |
| print("AUDIO WRITE ERROR:", e) | |
| return None | |
| return output_path | |