使用pyDub切碎长音频fi

2024-05-15 23:56:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用pyDub把一个长的WAV文件作为单独的单词(中间是silence)的输入,然后去掉所有的silence,输出剩下的块是单独的WAV文件。文件名可以是序列号,如001.wav、002.wav、003.wav等

Github页面上的“Yet another Example?”示例做了一些非常类似的事情,但它没有输出单独的文件,而是将静默剥离的片段组合到一个文件中:

from pydub import AudioSegment
from pydub.utils import db_to_float

# Let's load up the audio we need...
podcast = AudioSegment.from_mp3("podcast.mp3")
intro = AudioSegment.from_wav("intro.wav")
outro = AudioSegment.from_wav("outro.wav")

# Let's consider anything that is 30 decibels quieter than
# the average volume of the podcast to be silence
average_loudness = podcast.rms
silence_threshold = average_loudness * db_to_float(-30)

# filter out the silence
podcast_parts = (ms for ms in podcast if ms.rms > silence_threshold)

# combine all the chunks back together
podcast = reduce(lambda a, b: a + b, podcast_parts)

# add on the bumpers
podcast = intro + podcast + outro

# save the result
podcast.export("podcast_processed.mp3", format="mp3")

是否可以将这些podcast_部分片段作为单独的WAV文件输出?如果是,怎么做?

谢谢!


Tags: 文件thetofrommp3msaveragewav
1条回答
网友
1楼 · 发布于 2024-05-15 23:56:37

示例代码非常简单,您可能需要查看strip_silence函数:

https://github.com/jiaaro/pydub/blob/master/pydub/effects.py#L76

然后只导出每个块而不是组合它们。

示例和strip_silence函数之间的主要区别在于,示例查看的是一个毫秒的切片,这并不能很好地计算低频声音,因为例如,40hz声音的一个波形是25毫秒长。

不过,您最初的问题的答案是,原始音频段的所有片段也是音频段,因此您可以对它们调用export方法:)

更新:您可能需要查看一下我刚刚推到主分支中的silence utilities;特别是^{},它可以这样做(假设有正确的特定参数),如下所示:

from pydub import AudioSegment
from pydub.silence import split_on_silence

sound = AudioSegment.from_mp3("my_file.mp3")
chunks = split_on_silence(sound, 
    # must be silent for at least half a second
    min_silence_len=500,

    # consider it silent if quieter than -16 dBFS
    silence_thresh=-16
)

您可以将所有单独的块导出为wav文件,如下所示:

for i, chunk in enumerate(chunks):
    chunk.export("/path/to/ouput/dir/chunk{0}.wav".format(i), format="wav")

这将使每个输出名为“chunk0.wav”、“chunk1.wav”、“chunk2.wav”等

相关问题 更多 >