Auido VAD: Remove Silence in WAV Using Python – Python Tutorial

By | April 6, 2022

Audio VAD (Voice Activation Detection) can allow us to remove silence in a wav file. In this tutorial, we will introduce how to do.

Remove silence in audio file

In python, we can use python librosa library to remove, here is the tutorial:

Python Remove Silence in WAV Using Librosa – Librosa Tutorial

However, we also can create a VAD to remove.

Remove silence using VAD

In order to use VAD to remove silence, we should detect wich chunk is silence.

Here is an example:

import math
import logging
import numpy as np
import librosa
class SilenceDetector(object):
    def __init__(self, threshold=20, bits_per_sample=16):
        self.cur_SPL = 0
        self.threshold = threshold
        self.bits_per_sample = bits_per_sample
        self.normal = pow(2.0, bits_per_sample - 1);
        self.logger = logging.getLogger('balloon_thrift')


    def is_silence(self, chunk):
        self.cur_SPL = self.soundPressureLevel(chunk)
        is_sil = self.cur_SPL < self.threshold
        # print('cur spl=%f' % self.cur_SPL)
        if is_sil:
            self.logger.debug('cur spl=%f' % self.cur_SPL)
        return is_sil


    def soundPressureLevel(self, chunk):
        value = math.pow(self.localEnergy(chunk), 0.5)
        value = value / len(chunk) + 1e-12
        value = 20.0 * math.log(value, 10)
        return value

    def localEnergy(self, chunk):
        power = 0.0
        for i in range(len(chunk)):
            sample = chunk[i] * self.normal
            power += sample*sample
        return power

SilenceDetector class can detect a wave chunk is silent or not.

Then we can create a VAD to remove silence.

def VAD(audio, sampele_rate):
    chunk_size = int(sampele_rate*0.05) # 50ms
    index = 0
    sil_detector = silence_detector.SilenceDetector(15)
    nonsil_audio=[]
    while index + chunk_size < len(audio):
        if not sil_detector.is_silence(audio[index: index+chunk_size]):
            nonsil_audio.extend(audio[index: index + chunk_size])
        index += chunk_size

    return np.array(nonsil_audio)

In this VAD, we will set the length of each chunk to sampele_rate*0.05, if sample_rate = 8000, the chunk size will be 50ms.

Then, we can start to remove:

if __name__ == '__main__':

    sr = 8000
    audio, sr = librosa.load(r"D:\step-5000-audio.wav", sr=sr, mono=True)
    # audio: numpy.ndarray
    print(audio.shape)

    audio = VAD(audio.flatten(), sr)
    print(audio.shape)

Run this code, we will see:

(72242,)
(50000,)

We will find some silent chunks are removed.

You also can save audio without silence, you can view this tutorial:

Combine WAV Files to One File Using Python – Python Tutorial