Spaces:
Sleeping
Sleeping
Update beat_generator/riffusion_cpu.py
Browse files- beat_generator/riffusion_cpu.py +33 -17
beat_generator/riffusion_cpu.py
CHANGED
|
@@ -3,35 +3,51 @@ import soundfile as sf
|
|
| 3 |
import os
|
| 4 |
import uuid
|
| 5 |
|
|
|
|
| 6 |
def generate_audio_loop(style, bpm):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
sr = 44100
|
| 8 |
-
sec =
|
|
|
|
| 9 |
|
| 10 |
-
t = np.linspace(0, sec,
|
| 11 |
|
| 12 |
-
#
|
| 13 |
if style == "Country Rap":
|
| 14 |
-
freq =
|
| 15 |
elif style == "Trap":
|
| 16 |
-
freq =
|
| 17 |
elif style == "Dark Outlaw":
|
| 18 |
-
freq =
|
| 19 |
elif style == "Drill":
|
| 20 |
-
freq =
|
| 21 |
else:
|
| 22 |
-
freq =
|
| 23 |
|
| 24 |
-
|
|
|
|
| 25 |
|
| 26 |
-
#
|
| 27 |
-
|
| 28 |
-
|
|
|
|
| 29 |
|
| 30 |
-
|
|
|
|
| 31 |
|
| 32 |
-
|
| 33 |
-
|
|
|
|
| 34 |
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
return
|
|
|
|
| 3 |
import os
|
| 4 |
import uuid
|
| 5 |
|
| 6 |
+
|
| 7 |
def generate_audio_loop(style, bpm):
|
| 8 |
+
# Ensure directory exists
|
| 9 |
+
outdir = "assets/generated_beats"
|
| 10 |
+
os.makedirs(outdir, exist_ok=True)
|
| 11 |
+
|
| 12 |
+
# Audio settings
|
| 13 |
sr = 44100
|
| 14 |
+
sec = 5 # shorter = safer for HF
|
| 15 |
+
samples = int(sr * sec)
|
| 16 |
|
| 17 |
+
t = np.linspace(0, sec, samples)
|
| 18 |
|
| 19 |
+
# Pick a frequency based on style
|
| 20 |
if style == "Country Rap":
|
| 21 |
+
freq = 80 + bpm * 0.5
|
| 22 |
elif style == "Trap":
|
| 23 |
+
freq = 120 + bpm * 0.3
|
| 24 |
elif style == "Dark Outlaw":
|
| 25 |
+
freq = 60 + bpm * 0.4
|
| 26 |
elif style == "Drill":
|
| 27 |
+
freq = 150 + bpm * 0.2
|
| 28 |
else:
|
| 29 |
+
freq = 100 + bpm * 0.2
|
| 30 |
|
| 31 |
+
# Main tone
|
| 32 |
+
waveform = 0.3 * np.sin(2 * np.pi * freq * t)
|
| 33 |
|
| 34 |
+
# Add simple hi-hat clicks
|
| 35 |
+
for i in range(0, samples, int(sr * 0.2)):
|
| 36 |
+
if i < samples:
|
| 37 |
+
waveform[i:i+200] += 0.5 * np.random.uniform(-1, 1, 200)
|
| 38 |
|
| 39 |
+
# Normalize to float32
|
| 40 |
+
waveform = waveform.astype(np.float32)
|
| 41 |
|
| 42 |
+
# Output file path
|
| 43 |
+
filename = f"{uuid.uuid4().hex}.wav"
|
| 44 |
+
output_path = os.path.join(outdir, filename)
|
| 45 |
|
| 46 |
+
# Write audio
|
| 47 |
+
try:
|
| 48 |
+
sf.write(output_path, waveform, sr)
|
| 49 |
+
except Exception as e:
|
| 50 |
+
print("AUDIO WRITE ERROR:", e)
|
| 51 |
+
return None
|
| 52 |
|
| 53 |
+
return output_path
|