基于这个问题/答案的思路
# this is the threshold that determines whether or not sound is detected
THRESHOLD = 0
#open your audio stream
# wait until the sound data breaks some level threshold
while True:
data = stream.read(chunk)
# check level against threshold, you'll have to write getLevel()
if getLevel(data) > THRESHOLD:
break
# record for however long you want
# close the stream
import audioop
import pyaudio
chunk = 1024
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16,
channels=1,
rate=44100,
input=True,
frames_per_buffer=chunk)
data = stream.read(chunk)
rms = audioop.rms(data, 2) #width=2 for format=paInt16
如何操作在您提供的链接中有说明:
print "* recording"
for i in range(0, 44100 / chunk * RECORD_SECONDS):
data = stream.read(chunk)
# check for silence here by comparing the level with 0 (or some threshold) for
# the contents of data.
# then write data or not to a file
您需要设置阈值变量,并在每次循环中读取数据时与平均值(振幅)或其他相关参数进行比较。
您可以有两个嵌套的循环,第一个用于触发录音,另一个用于在此之后连续保存声音数据块。