【发布时间】:2011-02-09 17:44:22
【问题描述】:
我正在使用这个程序在 python 中录制声音:
Detect & Record Audio in Python
我想更改程序以在声卡输入检测到声音时开始录制。可能应该比较块中的输入声级,但是如何做到这一点?
【问题讨论】:
标签: python audio detect record
我正在使用这个程序在 python 中录制声音:
Detect & Record Audio in Python
我想更改程序以在声卡输入检测到声音时开始录制。可能应该比较块中的输入声级,但是如何做到这一点?
【问题讨论】:
标签: python audio detect record
你可以试试这样的:
# 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
您可能希望使用块大小和阈值,直到获得所需的行为。
编辑:
您可以使用内置的audioop 包来查找样本的均方根 (rms),这通常是您获得级别的方式。
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
每次在循环中读取时,您必须设置阈值变量并与数据中的平均值(幅度)或其他相关参数进行比较。
您可以有两个嵌套循环,第一个用于触发录制,另一个用于在此之后连续保存声音数据块。
【讨论】:
检测何时没有静音通常是通过使用某个声音块的root mean square(RMS) 并将其与您设置的某个阈值进行比较(该值将取决于您的麦克风的灵敏度和其他的东西,所以你必须调整它)。此外,根据您希望麦克风检测到录制声音的速度,您可能需要降低块大小,或计算重叠数据块的 RMS。
【讨论】: