2014-05-19 47 views
5

我想使用pyDub將單個單詞(以及兩者之間的靜音)的長WAV文件作爲輸入,然後去除所有沉默,並輸出剩餘的塊個人WAV文件。文件名可以是連續的數字,如001.wav,002.wav,003.wav等。使用pyDub砍掉一個長音頻文件

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_parts片段作爲單獨的WAV文件?如果是這樣,怎麼樣?

謝謝!

回答

7

的示例代碼是相當簡單的,你可能會想看看strip_silence功能:

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

然後就是導出的每個塊,而不是將它們組合起來的。

這個例子和strip_silence函數之間的主要區別在於這個例子看起來好像是一毫秒的時間片,因爲40Hz聲音的一個波形例如是25毫秒長,所以它不能很好的計算低頻聲音。

回答你原來的問題雖然是原始音頻段的所有這些切片也音頻片段,所以你可以要求他們導出方法:)

更新:您可能希望看看silence utilities我剛剛進入主分支;特別是split_on_silence()這可以這樣做(假設權的具體參數),像這樣:

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」等等

+0

感謝您的回覆,但我有點初學者,但我仍然不知道如何處理傳球將音頻片段轉換爲導出方法。 – user3643227