File size: 1,525 Bytes
1919bbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
"""

===============================================================================

preprocessing/silence_removal.py — Energy-Based Silence Trimming

===============================================================================



"""

import numpy as np
import librosa
from config import SILENCE_TOP_DB


def remove_silence(audio, sr):
    """

    Remove leading and trailing silence from the audio signal.



    Uses energy-based detection to find where the "real" sound starts and ends,

    then trims everything outside that window.



    Parameters

    ----------

    audio : np.ndarray

        1D array of audio samples.

    sr : int

        Sampling rate of the audio.



    Returns

    -------

    np.ndarray

        Trimmed audio signal. If the entire signal is below the threshold,

        returns the original audio unchanged (safety fallback).



    Notes

    -----

    - top_db is imported from config.py (default: 20 dB).

    - A small margin (frame_length=2048, hop_length=512) is used for

      energy estimation. These are independent of the mel spectrogram

      parameters — they only control how finely we detect silence boundaries.



    """
    # TODO (EL sir): Implement silence removal.
    
    trimmed_audio, index = librosa.effects.trim(
        audio,
        top_db=SILENCE_TOP_DB, 
        frame_length = 2048, 
        hop_length = 512
    )  
    if len(trimmed_audio) < 1024:   
        return audio                

    return trimmed_audio