【问题标题】:Adding silent frame to wav file using python使用python将静音帧添加到wav文件
【发布时间】:2018-03-27 05:44:13
【问题描述】:

第一次在这里发帖,让我们看看这是怎么回事。

我试图在 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> )

使用上面的代码,当我尝试添加静音时出现错误,因为音频长度与输入不同。

我对音频处理也很陌生,所以现在我只是在尝试任何东西,看看有什么效果。

任何建议或想法如何处理都会很棒:)。

我也在使用 python 2.7.5

非常感谢。

【问题讨论】:

    标签: python audio wave audio-processing


    【解决方案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)
    

    【讨论】:

    • 很酷,谢谢,这看起来更好,然后将一堆十六进制值组合在一起并只写出特定的音频值。试一试,就像魅力一样。
    • @Anil_M 太棒了。至于应该播放音频文件的最后一行,我收到错误AttributeError: 'str' object has no attribute 'export'
    猜你喜欢
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    • 2010-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多