Python使音频文件的特定部分静音

问题描述

我有一个音频文件 audio.wav 并且我有一系列看起来像这样的时间框架:

X = [(12.31,14.),(15.4,18.9),...]

这些是我希望在我拥有的 .wav 音频文件中完全静音的时间范围。我怎样才能做到这一点?

解决方法

根据您的链接,我将其视为

from pydub import AudioSegment

a = AudioSegment.from_wav("audio.wav")

# X = [(12.31,14.),(15.4,18.9),...]

duration = (14.0 - 12.31) * 1000
s1 = AudioSegment.silent(duration)

duration = (18.9 - 15.4) * 1000
s2 = AudioSegment.silent(duration)

b = a[:12310] + s1 + a[14000:15400] + s2 + a[18900:]

b.export('new_audio.wav',format='wav')

现在的问题是使用 for-loop 来自动化它

我无法测试,但我认为它是

from pydub import AudioSegment

a = AudioSegment.from_wav("audio.wav")

X = [(12.31,18.9)]

parts = []

# start for audio
begin = 0

for start,end in X:
    # keep sound before silence
    s = a[begin*1000:start*1000]
    parts.append(s)  
    
    # create silence
    duration = (end - start) * 1000
    s = AudioSegment.silent(duration)
    parts.append(s)

    # value for next loop
    begin = end

# keep part after last silence
parts.append(a[begin*1000:])

# join all parts using standard `sum()` but it need `parts[0]` as start value   
b = sum(parts[1:],parts[0])

# save it
b.export('new_audio.wav',format='wav')