使用python将无声帧添加到wav文件

使用python将无声帧添加到wav文件

问题描述:

第一次在这里发布,让我们看看这是怎么回事。使用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

非常感谢。

有许多可以用最少的代码量很容易地做到这样的音频处理的库。其中一个是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