Detect and record a sound with python

前端 未结 3 2066
闹比i
闹比i 2020-12-01 08:36

I\'m using this program to record a sound in python:

Detect & Record Audio in Python

I want to change the program to start recording when sound is detect

3条回答
  •  旧时难觅i
    2020-12-01 09:04

    You could try something like this:

    based on this question/answer

    # 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
    

    You'll probably want to play with your chunk size and threshold values until you get the desired behavior.

    Edit:

    You can use the built-in audioop package to find the root-mean-square (rms) of a sample, which is generally how you would get the level.

    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
    

提交回复
热议问题