szili2011's picture
Update app.py
31693e5 verified
raw
history blame
1.24 kB
import gradio as gr
import librosa
import numpy as np
import soundfile as sf
def reverse_segments_advanced(audio_path):
# Load audio with high precision
y, sr = librosa.load(audio_path, sr=None)
# Advanced BPM detection
onset_env = librosa.onset.onset_strength(y=y, sr=sr, aggregate=np.median)
tempo, beats = librosa.beat.beat_track(y=y, sr=sr, onset_envelope=onset_env, trim=False)
# Convert beats to exact sample positions
beat_frames = librosa.frames_to_samples(beats)
# Reverse the entire audio first
y_reversed = y[::-1]
# Cut into beat-aligned segments
segments = [y_reversed[beat_frames[i]:beat_frames[i+1]] for i in range(len(beat_frames)-1)]
# Reverse each segment back to forward
processed_audio = np.concatenate([segment[::-1] for segment in segments])
# Save the output
output_path = "output.wav"
sf.write(output_path, processed_audio, sr)
return output_path
iface = gr.Interface(
fn=reverse_segments_advanced,
inputs=gr.Audio(type="filepath"),
outputs=gr.Audio(),
title="High-Precision Beat-Reversed Music",
description="More accurate BPM detection for reversing music and playing beat-aligned segments forward."
)
iface.launch()