如何在wav文件前添加静音

Sam*_*ame 6 python audio wav

我是python的新手.我正在进行一项利用音频(WAV)文件的实验.我有超过100个可变长度的音频文件.其中最长的是10秒.但是对于我的实验,我需要所有文件具有相同的长度,即10秒.所以我想在这些文件前面加上几秒钟的静音,长度不到10秒.

那么如何用python将静音添加到WAV文件的开头呢?可变长度的沉默

joj*_*jek 4

我做了一个小脚本,它允许您在信号前面加上静音,以获得以秒为单位的目标持续时间。它使用 scipy 函数来读取 wav 文件。

#!/usr/bin/env python

from __future__ import print_function, division
import scipy.io.wavfile as wavf
import numpy as np
from sys import argv

def pad_audio(data, fs, T):
    # Calculate target number of samples
    N_tar = int(fs * T)
    # Calculate number of zero samples to append
    shape = data.shape
    # Create the target shape    
    N_pad = N_tar - shape[0]
    print("Padding with %s seconds of silence" % str(N_pad/fs) )
    shape = (N_pad,) + shape[1:]
    # Stack only if there is something to append    
    if shape[0] > 0:                
        if len(shape) > 1:
            return np.vstack((np.zeros(shape),
                              data))
        else:
            return np.hstack((np.zeros(shape),
                              data))
    else:
        return data

if __name__ == "__main__":
    if len(argv) != 4:
        print("Wrong arguments.")
        print("Use: %s in.wav out.wav target_time_s" % argv[0])
    else:
        in_wav = argv[1]
        out_wav = argv[2]
        T = float(argv[3])        
        # Read the wav file
        fs, in_data = wavf.read(in_wav)
        # Prepend with zeros
        out_data = pad_audio(in_data, fs, T)
        # Save the output file
        wavf.write(out_wav, fs, out_data)
Run Code Online (Sandbox Code Playgroud)