用python检测并录制声音

Jea*_*rre 11 python audio record detect

我正在使用这个程序在python中录制声音:

用Python检测和录制音频

我想更改程序,以便在声卡输入检测到声音时开始录制.可能应该比较块中的输入声级,但是这怎么做?

tgr*_*ray 11

你可以尝试这样的事情:

基于这个问题/答案

# 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
Run Code Online (Sandbox Code Playgroud)

您可能希望使用块大小和阈值,直到获得所需的行为.

编辑:

您可以使用内置的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
Run Code Online (Sandbox Code Playgroud)


Jus*_*eel 5

检测时,没有沉默是通过使用通常做均方根(RMS)的声音有些大块的,并与您设置一些阈值进行比较(该值将取决于你的麦克风是多么敏感和其他东西,所以你必须调整它).此外,根据您希望麦克风检测声音的速度,您可能需要降低块大小,或者计算重叠数据块的RMS.