Recording automatically ends the recording python

# - * - Coding: UTF-8 - * - 
Import pyaudio
Import numpy AS NP
from SciPy Import fftpack
Import Wave


# Record
# portaudio recording module must be installed, otherwise it will error
# http://portaudio.com/docs/v19-doxydocs /compile_linux.html
DEF recording (filename, time = 0, threshold = 7000):
"" "
: param filename: file name
: param time: recording time, if the specified time, according to the recording time, the default is to automatically identify whether the end of the recording
: param threshold: determining a threshold recording is ended
: return:
"" "
the CHUNK block size = 1024 #
FORMAT = pyaudio.paInt16 # bits per acquisition
cHANNELS = 1 # number of channels
rATE = 16000 # sampling rate: second acquisition the number of data
RECORD_SECONDS = time # recording time
WAVE_OUTPUT_FILENAME = filename # file location
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK)
print("* 录音中...")
frames = []
if time > 0:
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
else:
stopflag = 0
stopflag2 = 0
while True:
data = stream.read(CHUNK)
rt_data = np.frombuffer(data, np.dtype('<i2'))
# print(rt_data*10)
# 傅里叶变换
fft_temp_data = fftpack.fft(rt_data, rt_data.size, overwrite_x=True)
= np.abs fft_data (fft_temp_data) [0: // fft_temp_data.size. 1 + 2]

# test threshold, the output value of the threshold value for judging
Print (SUM (fft_data) // len (fft_data))

# determines whether or not the microphone is stopped, it is determined talk has ended, # microphone threshold, default 7000
iF SUM (fft_data) // len (fft_data)> threshold:
StopFlag + = 1
the else:
stopflag2 + = 1
oneSecond = int (the RATE / CHUNK)
iF stopflag2 + StopFlag> oneSecond:
iF stopflag2> // oneSecond. 3 * 2:
BREAK
the else:
stopflag2 = 0
StopFlag = 0
frames.append (Data)
Print ( "recording end *")
stream.stop_stream ()
stream.close ()
p.terminate ()
with wave.open (WAVE_OUTPUT_FILENAME, 'WB') AS WF:
wf.setnchannels (the CHANNELS)
wf.setsampwidth (p.get_sample_size (the FORMAT))
wf.setframerate ( the RATE)
wf.writeframes (B ''. the Join (Frames))


# recording ( 'ppp.mp3', = time. 5) # according to the recording time, recording five seconds
recording ( 'ppp.mp3') # no sound is automatically stopped ,Automatic stop

Guess you like

Origin www.cnblogs.com/chenxiyuxiao/p/11326714.html