繁体   English   中英

使用python向wav文件添加静音帧

[英]Adding silent frame to wav file using python

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

我试图用 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

非常感谢。

有些库可以用最少的代码轻松地进行这些类型的音频操作。 pydub就是其中之一

您可以按如下方式安装pydub ,有关依赖项的详细信息在这里
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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM