import io
import librosa
import soundfile as sf


def trim_silence_from_audio_bytes(audio_bytes):

    # Load the audio data from bytes
    audio_file = io.BytesIO(audio_bytes)
    y, sr = librosa.load(audio_file, sr=None)

    # Trim silence from the beginning and end
    yt, index = librosa.effects.trim(y, top_db=30)  # Adjust top_db as needed

    # Convert the trimmed audio back to bytes
    trimmed_audio_file = io.BytesIO()
    sf.write(trimmed_audio_file, yt, sr, format='WAV')
    trimmed_audio_bytes = trimmed_audio_file.getvalue()

    return trimmed_audio_bytes