2017-10-15 65 views
2

第一次在這裏發佈,讓我們看看這是怎麼回事。使用python將無聲幀添加到wav文件

我試圖在python中編寫一個腳本,它會在wav文件的開頭添加第二個沉默,但是到目前爲止這樣做沒有成功。

我想要做的是在wav頭文件中讀取,然後使用wave模塊添加一個\ 0開始,但那樣做效果不好。這裏是從這裏http://andrewslotnick.com/posts/audio-delay-with-python.html

import wave 
from audioop import add 

def input_wave(filename,frames=10000000): #10000000 is an arbitrary large number of frames 
    wave_file = wave.open(filename,'rb') 
    params=wave_file.getparams() 
    audio=wave_file.readframes(frames) 
    wave_file.close() 

    return params, audio 

#output to file so we can use ipython notebook's Audio widget 
def output_wave(audio, params, stem, suffix): 
    #dynamically format the filename by passing in data 
    filename=stem.replace('.wav','_{}.wav'.format(suffix)) 
    wave_file = wave.open(filename,'wb') 
    wave_file.setparams(params) 
    wave_file.writeframes(audio) 

# delay the audio 
def delay(audio_bytes,params,offset_ms): 
    """version 1: delay after 'offset_ms' milliseconds""" 
    #calculate the number of bytes which corresponds to the offset in milliseconds 
    offset= params[0]*offset_ms*int(params[2]/1000) 
    #create some silence 
    beginning= b'\0' 
    #remove space from the end 
    end= audio_bytes   
    return add(audio_bytes, beginning+end, params[0]) 

audio_params, aduio_bytes = input_wave(<audio_file>) 
output_wave(delay(aduio_bytes,audio_params,10000), audio_params, <audio_file>, <audio_file_suffics>) 

基於使用上面的代碼中,我得到一個錯誤,如果我嘗試添加了沉默作爲音頻lenght是不一樣的,輸入的代碼。

我也是很新的音頻處理所以現在我只是想什麼,seig什麼堅持。

任何意見或想法如何處理將是巨大的:)。

我也是使用Python 2.7.5

非常感謝。

回答

1

有許多可以用最少的代碼量很容易地做到這樣的音頻處理的庫。其中一個是pydub

您可以安裝pydub下面和有關相關細節都here
pip install pydub

使用pydub,你可以閱讀不同的音頻格式(在這種情況下wav),並將其轉換爲音頻段,然後再進行操作或只是玩它。

您還可以創建設定時段的靜默音頻段,並添加兩段用「+」操作符。

源代碼

from pydub import AudioSegment 
from pydub.playback import play 

audio_in_file = "in_sine.wav" 
audio_out_file = "out_sine.wav" 

# create 1 sec of silence audio segment 
one_sec_segment = AudioSegment.silent(duration=1000) #duration in milliseconds 

#read wav file to an audio segment 
song = AudioSegment.from_wav(audio_in_file) 

#Add above two audio segments  
final_song = one_sec_segment + song 

#Either save modified audio 
final_song.export(audio_out_file, format="wav") 

#Or Play modified audio 
play(final_song) 
+0

酷感謝,看起來更好的方式相結合,然後一羣十六進制值在一起,寫出只有特定的音頻值。給它一個去,就像一個魅力。 – Madmax

相關問題